DarkRiftNetworking / Hazel-Networking

Hazel Networking is a low level networking library for C# providing connection orientated, message based communication via TCP, UDP and RUDP.
http://www.darkriftnetworking.com
MIT License
206 stars 44 forks source link

TCP does not maintain ordering #14

Open Rich2020 opened 6 years ago

Rich2020 commented 6 years ago

I am sending from my client to a server using connection.SendBytes(bytes, SendOption.Reliable); but the server still receives the messages in the incorrect order.

To test this, my server simply has a ConcurrentQueue which is populated when the Receive callback is fired. I have a Task which loops and uses var success = queue.TryTake(out message); - if successful, I deserialize and check the number of the message received. After some random amount of messages, it is clear that the messages received are not always in the correct order. I am certain that I have sent them in the correct order.

JamJar00 commented 6 years ago

You are correct, messages in TCP are not guaranteed to remain in order in Hazel, that is intended behaviour though.

It's because Hazel starts the next receive operation before invoking the event for better throughput, so if there's buffered messages and unlucky CPU scheduling you can have the event trigger for a later message before the earlier message.

You should be able to fix the ordering so its order doesn't change by moving line 203 of TcpConnection to the start of the message 🙂

An option to enable/disable this could be a neat pull request if you like!

JamJar00 commented 6 years ago

I changed the title just so it's a bit more reflective of the actual issue, I hope you don't mind.

Jamie

Rich2020 commented 6 years ago

Thanks for getting back to me. No problem changing the title. I'll take a look at what you have mentioned and get back to you (probably tomorrow sometime). :)