How to get all data from NetworkStream

前端 未结 7 2163
执念已碎
执念已碎 2020-12-01 08:45

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

7条回答
  •  暖寄归人
    2020-12-01 08:58

    Try this code:

    using (NetworkStream stream = client.GetStream())
        {
             while (!stream.DataAvailable)
             {
                 Thread.Sleep(20);
             }
            
             if (stream.DataAvailable && stream.CanRead)
             {
                  Byte[] data = new Byte[1024];
                  List allData = new List();
            
                  do
                  {
                        int numBytesRead = stream.Read(data,0,data.Length);
        
                        if (numBytesRead == data.Length)
                        {
                             allData.AddRange(data);
                        }
                        else if (numBytesRead > 0)
                        {
                             allData.AddRange(data.Take(numBytesRead));
                        }                                    
                   } while (stream.DataAvailable);
              }
        }
          
    

    Hope this helps, it should prevent that you miss any data sended to you.

提交回复
热议问题