1


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();
}
2
  • Are you clearing bytesFrom before second read? I suspect your buffer bytesFrom has old data in it! Commented Feb 23, 2015 at 9:52
  • Are you sure the server is seeing the full "999999999" on the first read? Commented Feb 23, 2015 at 9:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.