c# - 防御无数据
问题描述
我有这行代码:
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
是非常不可靠的。如何防御空消息?
解决方案
你为什么需要那个?您可以使用 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());
}
}
测试和工作。
推荐阅读
- c# - 无法在 C# 中将类型 void 隐式转换为 int
- c# - 将单个 KeyValuePair<> 序列化为 JSON 作为父对象的一部分
- css - 如何在 CSS 中设置自定义 HR 元素的样式?
- python - Django 没有识别出我的模型中有对象
- java - 在Java中没有Scanner.class的k-shingles中的分隔文本
- vert.x - 如何从 VertX Future 对象中获取值
- c++ - 允许调用者在我的 Builder 类中使用任何指针类型(包括智能指针)?
- sql - PL/SQL 和 SQL Developer 的结果不同
- swift - PushViewController 显示黑屏
- angular - 如何在 Ionic 5 中获得 canGoBack 功能?