简体   繁体   English

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

[英]NetworkStream.Read() produce repetitive bytes when reading in loop

I'm reading all DataAvailable from NetworkStream in a while loop and in every cycle I'm reading available data with a specific chunk size: 我在while循环中从NetworkStream读取所有DataAvailable ,在每个周期中,我正在读取具有特定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;

Problem is in output I get some random texts from middle of my received bytes, I mean something similar to this: 问题出在输出中,我从接收到的字节中间得到一些随机文本,我的意思是这样的:

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

What makes me confused is that if I increase chunk size from 2048 to 3072 this problem will not happen. 让我感到困惑的是,如果我将块大小从2048增加到3072则不会发生此问题。

I also traced TcpClient.Available with a breakpoint in each cycle: 我还跟踪了每个周期中带有断点的TcpClient.Available

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

I would have thought that this: 我本以为是这样的:

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

should be this: 应该是这样的:

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

That ensures that only data read on this specific occasion will be included in the output. 这样可以确保仅将在此特定情况下读取的数据包括在输出中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM