TCP socket programming, strange behavior when read data


I'm writing tcp socket program.
When I send string, shorter than previous sending, from client and receive it on server, something strange happening. For example:
First I send '999999999'. Server receives finely.
After that, I send shorter string: '7777777'. But the data on server is '777777799'.

Why the previous data's remnant is still alive on next sending?

My code is below:

// Section: client sending data ----
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = Encoding.ASCII.GetBytes("999999999");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();

// Section: Server reading data ----
while ((true))
{
    NetworkStream networkStream = clientSocket.GetStream();
    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
    dataFromClient = Encoding.ASCII.GetString(bytesFrom);
    networkStream.Flush();
}
Jon Skeet
people
quotationmark

You're ignoring the amount of data you've read, instead always converting the whole byte array into a string, including any data which is still present from a previous read (or the initial byte array elements). You should have:

int bytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
dataFromClient = Encoding.ASCII.GetString(bytesFrom. 0, bytesRead);

Note that I've changed the third argument to networkStream.Read, too - otherwise if there's more data than you have space for in the array, you'll get an exception. (If you really want to use ReceiveBufferSize, then create the array for that length.)

Also, you should check that bytesRead is positive - otherwise you'll get an exception if the connection is closed.

Basically, you should pretty much never ignore the return value of Stream.Read.

people

See more on this question at Stackoverflow