Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate messages in a binary networkStream?

I'm encoding, sending and decoding data using sockets/networkStream. But how can I effectively separate messages from each other ?

For example, when I use a 1024 byte buffer, then receive stuff via networkStream. Then I wanna pass that buffer on to my decoder class, but I'm not sure if part of the next message is already lurking in the buffer. If my message has only 50 bytes, how do I know that there are not 20 messages in that buffer ? Or worse, could there be partial messages in my buffer ?

Let's say my message has 3000 bytes, could there be a message and the start of a second message in a buffer? Or does networkStream automatically receive messages in packages as they were sent ?

like image 880
pixartist Avatar asked Dec 30 '25 19:12

pixartist


1 Answers

There are two general choices:

  • Send a fixed size header that specifies exactly how long the following message is.
  • Send the message followed by a terminator that cannot appear within the message.

All methods of sending variable size binary data through a socket are variations on one of these two themes.

like image 200
Greg Hewgill Avatar answered Jan 02 '26 09:01

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!