Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket ReceiveAsync merging packets

I intend to receive packets of data over a socket but since they are sent from the sender with a high frequency a number of them get packed into a single byte array. SocketAsyncEventArgs.Buffer then holds multiple packets, even though they were sent separately (verified using wireshark).

I have already tried to queue the incoming packets and asynchronously work them off, but still I get the same result.

What could be reason for this behaviour?

like image 284
korve Avatar asked Jan 22 '26 09:01

korve


1 Answers

This is how TCP works. TCP connection is a bi-directional stream of bytes, and you have to treat it as such. Single send from one end might result in multiple reads on the receiving side, and vice versa, multiple sends might end up in a single read, and application message boundaries are not preserved by the transport.

You have to buffer the input until you know you have a complete application message. Common approaches are:

  • fixed length messages,
  • pre-pending length in front of the message,
  • delimiting the stream with special "end-of-message" separator.
like image 128
Nikolai Fetissov Avatar answered Jan 25 '26 00:01

Nikolai Fetissov