TCP套接字编程,读取数据时的奇怪行为

问题描述:

我正在编写tcp套接字程序。

当我从客户端发送字符串,比之前的发送短,并在服务器上接收它时,发生了一些奇怪的事情。例如:

首先我发送'999999999'。服务器接收得很好。

之后,我发送更短的字符串:'7777777'。但服务器上的数据是'777777799'。



为什么以前数据的剩余部分在下次发送时仍然存在?



我的代码如下:



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();
}

在读取数据时,您需要确定从流中获取的数据量(缓冲区不会总是很满意。

clientSocket.ReceiveBufferSize 不告诉你缓冲了多少数据,它只告诉你用了多少内存来缓冲。

尝试这样的事情:

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:
int count = networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.ASCII.GetString(bytesFrom, 0, count);