网络套接字上的 C# BinaryReader.ReadString
我有一个服务器/客户端应用程序。
两者在通信时都使用BinaryReader/Writer。
当客户端和服务器快速交换消息时(在给定的一秒内有很多消息),并且我大多数时候(但并非总是)关闭服务器(通过内置命令,有序关闭),客户端的 BinaryReader.ReadString() 方法会抛出EndOfStreamException,这很好。我不明白的是为什么这个异常不将 TcpClient.Connected 属性更改为“false”?
while(true){
try{
BinaryReader.ReadString()
}
catch(IOException){
if(!TcpClient.Connected)
break;
//BinaryWriter.Write() - this will, eventually, change Connected property to 'false'
}
}
这将无限循环。我认为 Connected 属性会在网络读/写失败时发生变化。如果 BinaryReader 抛出异常,那么它没有成功读取,是吗?
如果我放入 BinaryWriter.Write(),则无限循环将被打破,因为 Connected 属性更改为“false”。
相关问题,EndOfStreamException 是否始终表明网络连接断开,或者是否意味着临时问题?
I have a server/client app.
Both use BinaryReader/Writer when communicating.
When the client and server are exchanging messages rapidly, many in a given second, and I shutdown the server (via a built in command, orderly shutdown) most of the time (but not always) the client's BinaryReader.ReadString() method throws a EndOfStreamException, which is fine. The thing that I don't understand is why doesn't this exception change the TcpClient.Connected property to 'false'?
while(true){
try{
BinaryReader.ReadString()
}
catch(IOException){
if(!TcpClient.Connected)
break;
//BinaryWriter.Write() - this will, eventually, change Connected property to 'false'
}
}
This will loop endlessly. I thought that the Connected property changes on unsuccessful network read/write. If BinaryReader is throwing exceptions then it isn't successfully reading, is it?
If I throw in a BinaryWriter.Write(), then the endless loop is broken because Connected property is changed to 'false'.
Related question, does an EndOfStreamException always indicate a broken network connection or could it mean a temporary problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过设计。来自 TcpClient.Connected 的 MSDN 库文章的备注部分:
您发现的解决方法是正确的。
By design. From the Remarks section of the MSDN Library article for TcpClient.Connected:
The workaround you discovered is the correct one.