Hazel-Networking
Hazel-Networking copied to clipboard
TCP does not maintain ordering
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 ConcurrentQueueTask
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.
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!
I changed the title just so it's a bit more reflective of the actual issue, I hope you don't mind.
Jamie
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). :)