TCP套接字编程,读取数据时的奇怪行为 [英] TCP socket programming, strange behavior when read data

查看:113
本文介绍了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);


这篇关于TCP套接字编程,读取数据时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆