如何从 NetworkStream 获取所有数据 [英] How to get all data from NetworkStream

查看:25
本文介绍了如何从 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 字节),您将无法获取所有数据,因此您必须读取循环内的流.然后你可以WriteMemoryStream中的所有数据,直到NetworkStream结束.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆