Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

C#
// 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();
}
Posted
Comments
Richard MacCutchan 23-Feb-15 5:06am    
You are just seeing the previous message's data that was left in the buffer. You need to extract only the number of characters that you receive.

1 solution

When reading data, you need to determine how much data was really taken from the stream (buffer will not always be full).
The clientSocket.ReceiveBufferSize does not tell you how much data was buffered, it only tells how much memory is used for buffering.
Try something like this:
C#
int count = networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, count);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900