I just read an article that says TCPClient.Read() may not get all the sent bytes in one read. How do you account for this?
For example, the server can write a string to the tcp stream. The client reads half of the string’s bytes, and then reads the other half in another read call.
how do you know when you need to combine the byte arrays received in both calls?
You need to decide this at the protocol level. There are four common models:
Additionally, less commonly, there are protocols where each message is always a particular size – in which case you just need to keep going until you’ve read that much data.
In all of these cases, you basically need to loop, reading data into some sort of buffer until you’ve got enough of it, however you determine that. You should always use the return value of
Readto note how many bytes you actually read, and always check whether it’s 0, in which case you’ve reached the end of the stream.Also note that this doesn’t just affect network streams – for anything other than a local
MemoryStream(which will always read as much data as you ask for in one go, if it’s in the stream at all), you should assume that data may only become available over the course of multiple calls.