Question

My Server will send a message using networkStream.Write(messageBytes);

My Client will receive the message using networkStream.Read(). The client will read byte by byte for a sequence, when it has found the sequence it reads the rest of the header.

The header contains a payload length. Once I have this I read the stream using the payload length to get the payload.

My problem is when I write the data, my client will try to read straight away and all the data may not have been written by this point.

So I end up with a message with the end effectively chopped off:

"blablablablabl\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"

Is there anyway to wait for all the information to be received?

Thanks.

Was it helpful?

Solution

This doesn't really make sense. Socket read functions tell you how much data is available / has been read into the buffer, so if you're processing a bunch of NULs in the buffer because the rest of the data hasn't been received, that's on you for not checking how much data has been received. If you're expecting more data, keep receiving until you get as much as you're expecting (avoid overwriting the previously-received chunks by advancing the pointer into the receive buffer or copying to a new buffer, etc).

OTHER TIPS

System network buffers are not infinite, if you dont read them from windows socket to your internal memory, they will stop receiving.

In the case, you might want to create a memory storage for your data:

byte[] data = new byte[dataLength];

And keep pushing data into the array until it is all read up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top