![](/img/trans.png)
[英]NetworkStream.Read() not correctly reading after first iteration of loop
[英]NetworkStream.Read() produce repetitive bytes when reading in loop
我在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;
問題出在輸出中,我從接收到的字節中間得到一些隨機文本,我的意思是這樣的:
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);
這樣可以確保僅將在此特定情況下讀取的數據包括在輸出中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.