Hazel-Networking icon indicating copy to clipboard operation
Hazel-Networking copied to clipboard

TCP does not maintain ordering

Open Rich2020 opened this issue 6 years ago • 3 comments

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.

Rich2020 avatar Jul 23 '18 16:07 Rich2020

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 avatar Jul 23 '18 17:07 JamJar00

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

Jamie

JamJar00 avatar Jul 23 '18 17:07 JamJar00

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). :)

Rich2020 avatar Jul 23 '18 18:07 Rich2020