C# NetworkStream.Read()在循环中读取时产生重复字节

C# NetworkStream.Read()在循环中读取时产生重复字节,c#,tcpclient,networkstream,C#,Tcpclient,Networkstream,我在循环中读取网络流中的所有DataAvailable,在每个循环中,我读取具有特定块大小的可用数据: 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 {

我在
循环中读取
网络流中的所有
DataAvailable
,在每个循环中,我读取具有特定
块大小的可用数据:

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

我本以为:

output += System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
应该是这样的:

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

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

我本以为:

output += System.Text.Encoding.ASCII.GetString(data, 0, data.Length);
应该是这样的:

output += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
这确保了输出中只包含在该特定场合读取的数据