在循环读取时,NetworkStream.Read()会产生重复的字节

时间:2018-04-29 04:38:10

标签: c# tcpclient networkstream

我正在DataAvailable循环中阅读NetworkStream的所有while,并且在每个周期中我都在阅读具有chunk特定尺寸的可用数据:

TcpClient client = new TcpClient("server address", 23);
NetworkStream stream = client.GetStream();

byte[] data = new byte[2048]; // read in chunks of 2KB
int bytesRead;
string output = "";

do
{
    bytesRead = stream.Read(data, 0, data.Length);
    output += System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
} while (stream.DataAvailable);

return output;

问题出在输出中我从收到的字节中间得到一些随机文本,我的意思是类似的东西:

1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J //here my output must finish but random bytes from middle append to the end:
3 C //repetitive bytes
4 D //repetitive bytes
5 E //repetitive bytes

令我困惑的是,如果我将块大小从2048增加到3072,则不会发生此问题。

我还在每个周期跟踪TcpClient.Available一个断点:

First cycle -> 4495
Second cycle -> 2447
Third cycle -> 399
Forth cycle -> 0

1 个答案:

答案 0 :(得分:3)

我原以为:

output += System.Text.Encoding.ASCII.GetString(data, 0, data.Length);

应该是这样的:

output += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);

确保只有在特定场合读取的数据才会包含在输出中。