I've both a client and a server communicating through TCP.
The client uses the NetworkStream to send info to the server that reads it back, then the process continues until the user wants to exit and close the connection. The problem is that the NetworkStream is dirty with a previous write. So let's suppose the client sends the string "aa "during the first time, and "b" during the second. On the second read the server will get "ba". What's missing here? Shouldn't the NetworkStream be consumed during the server reads? Here`s the relevant code ...

1 Answer
1

The above call decodes the entire buffer each time, despite that each message would only be written to the first n bytes of it (where n is the message length). Your first message, "aa", is written to the first two bytes of the buffer. Your second message, "b", is written to just the first byte, overwriting the first 'a' character but leaving the second 'a' intact. This is why the buffer appears to contain "ba" after your second message.

However, your code would still be susceptible to another issue: NetworkStream.Read only reads as much data as is currently available. If the client is still transmitting, then it might return a partial message. So your server might read the two messages as "a" and "ab".

In your case, since you seem to be transmitting single-line text messages only, you could wrap the NetworkStream in a StreamReader in the server, and in a StreamWriter in the client. Then, simply call StreamReader.ReadLine on the server, and StreamWriter.WriteLine on the client. ReadLine will keep reading until it encounters a newline, and will return null when the end of the stream is reached.