首页 > 解决方案 > 防御无数据

问题描述

我有这行代码:

NetworkStream tcpStream;
return IPAddress.NetworkToHostOrder(new BinaryReader(tcpStream).ReadInt32());

有时,没有要读取的数据并且该行会引发异常。

System.IO.EndOfStreamException
  HResult=0x80070026
  Message=Unable to read beyond the end of the stream.
  Source=mscorlib
  StackTrace:
   at System.IO.__Error.EndOfFile()
   at System.IO.BinaryReader.FillBuffer(Int32 numBytes)
   at System.IO.BinaryReader.ReadInt32()
   ...

Length物业似乎也没有帮助。DataAvailable是非常不可靠的。如何防御空消息?

标签: c#.nettcp

解决方案


你为什么需要那个?您可以使用 StreamReader 和 StreamWriter 轻松发送和接收字符串。然后,您可以处理该数据,并获取您的 int。

        static int Receive(NetworkStream nw)
        {
            using (var reader = new StreamReader(nw, Encoding.UTF8))
            {
                return Convert.ToInt32(reader.ReadLine());
            }
        }

        static void Send(NetworkStream nw, int num)
        {
            using (var writer = new StreamWriter(nw, Encoding.UTF8))
            {
                writer.WriteLine(num.ToString());
            }
        }

测试和工作。


推荐阅读