当互联网断开连接时,TcpClient.BeginRead/TcpClient.EndRead 不会抛出异常
我正在使用 TcpListener
来接受 &从 TcpClient
读取。 问题是,当从 TcpClient
读取时,TcpClient.BeginRead
/ TcpClient.EndRead
在互联网断开连接时不会抛出异常。仅当客户端进程结束或服务器或客户端关闭连接时,它才会引发异常。
I'm using TcpListener
to accept & read from TcpClient
.
The problem is that when reading from a TcpClient
, TcpClient.BeginRead
/ TcpClient.EndRead
doesn't throw exception when the internet is disconnected. It throws exception only if client's process is ended or connection is closed by server or client.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
系统通常没有机会知道连接已断开。知道这一点的唯一可靠方法是尝试发送一些东西。当您执行此操作时,数据包将被发送,然后丢失或退回,并且您的系统知道连接不再可用,并通过错误代码或异常(取决于环境)向您报告问题。读取通常是不够的,因为读取只检查输入缓冲区的状态,而不将数据包发送到远程端。
The system generally has no chance to know that connection is broken. The only reliable way to know this is to attempt to send something. When you do this, the packet is sent, then lost or bounced and your system knows that connection is no longer available, and reports the problem back to you by error code or exception (depending on environment). Reading is usually not enough cause reading only checks the state of input buffer, and doesn't send the packet to the remote side.
据我所知,在这种情况下,低级套接字不会通知您。您应该提供自己的超时实现或定期 ping 服务器。
As far as I know, low level sockets doesn't notify you in such cases. You should provide your own time out implementation or ping the server periodically.
如果您想了解网络状态何时发生变化,可以订阅
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
事件。这不是特定于互联网,而是特定于本地网络。编辑
抱歉,我误解了。越想越觉得“互联”这个概念确实不存在。 这篇文章很好地探讨了有关于此的更多详细信息。
TcpClient
上有一个Connected
属性,但 MSDN 说(强调我的):基本上,检查客户端连接的唯一方法是尝试发送数据。如果成功,则表示您已连接。如果失败了,你就不是。
If you want to know about when the network status changes you can subscribe to the
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
event. This is not specific to the internet, just the local network.EDIT
Sorry, I misunderstood. The concept of "connected" really doesn't exist the more you think about it. This post does a great job of going into more details about that. There is a
Connected
property on theTcpClient
but MSDN says (emphasis mine):Basically the only way to check for a client connection it to try to send data. If it goes through, you're connected. If it fails, you're not.
我认为您不希望 BeginRead 和 EndRead 抛出异常,因为它们应该在多线程场景中使用。
您可能需要实现一些其他机制来响应连接的断开。
I don't think you'd want BeginRead and EndRead throwing exceptions as these should be use in multi threaded scenarios.
You probably need to implement some other mechanism to respond to the dropping of a connection.