如何获得的NetworkStream的所有数据 [英] How to get all data from NetworkStream
问题描述
我想通过 TCP / IP
阅读出现在连接机缓存中的所有数据,但我不知道为什么我没有得到所有的数据,一些数据是越来越错过。
下面是我用用。
I am trying to read all data present in the buffer of the Machine connected through TCP/IP
but i don't know why i am not getting all data ,some data is getting Missed.
Here is the code that i am using ..
using (NetworkStream stream = client.GetStream())
{
byte[] data = new byte[1024];
int numBytesRead = stream.Read(data, 0, data.Length);
if (numBytesRead > 0)
{
string str= Encoding.ASCII.GetString(data, 0, numBytesRead);
}
}
请告诉我,我很想念让所有的从机器的数据。提前
谢谢..
Please tell me what i am missing to get all the data from the machine. Thanks in advance..
推荐答案
你的代码的问题是,你不会得到,如果所有的数据数据大小大于缓冲区大小(在你的案件1024字节)更大,所以你必须阅读循环内的数据流。然后,你可以写
在的MemoryStream
直至结束的NetworkStream 全部数据code>。
The problem with your code is that you will not get all the data if the data size is bigger than the buffer size (1024 bytes in your case) so you have to Read the stream inside the loop. Then you can Write
all the data inside a MemoryStream
until the end of the NetworkStream
.
结果
string str;
using (NetworkStream stream = client.GetStream())
{
byte[] data = new byte[1024];
using (MemoryStream ms = new MemoryStream())
{
int numBytesRead ;
while ((numBytesRead = stream.Read(data, 0, data.Length)) > 0)
{
ms.Write(data, 0, numBytesRead);
}
str = Encoding.ASCII.GetString(ms.ToArray(), 0, (int)ms.Length);
}
}
这篇关于如何获得的NetworkStream的所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!