Question

In a TcpClient/TcpListener set up, is there any difference from the receiving end point of view between:

// Will sending a prefixed length before the data...
client.GetStream().Write(data, 0, 4); // Int32 payload size = 80000
client.GetStream().Write(data, 0, 80000); // payload

// Appear as 80004 bytes in the stream?
// i.e. there is no end of stream to demarcate the first Write() from the second?
client.GetStream().Write(data, 0, 80004);

// Which means I can potentially read more than 4 bytes on the first read
var read = client.GetStream().Read(buffer, 0, 4082); // read could be any value from 0 to 4082?

I noticed that DataAvailable and return value of GetStream().Read() does not reliably tell whether there are incoming data on the way. Do I always need to write a Read() loop to exactly read the first 4 bytes?

// Read() loop
var ms = new MemoryStream()
while(ms.length < 4)
{
    read = client.GetStream().Read(buffer, 0, 4 - ms.length);
    if(read > 0)
        ms.Write(buffer, 0, read);
}
Was it helpful?

Solution

The answer seems to be yes, we have to always be responsible for reading the same number of bytes that was sent. In other words, there has to be an application level protocol to read exactly what was written on to the underlying stream because it does not know when a new message start or ends.

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