[英]How to know server connection is lost in client side
I have a tcp server that writes in winforms and a client in android. 我有一个用winforms编写的tcp服务器和一个android中的客户端。 I connect devices to a wirless network then I disconnect server from this network. 我将设备连接到无线网络,然后断开服务器与该网络的连接。 However client continue to listen server for a while then it closes its socket. 但是客户端继续监听服务器一段时间,然后关闭其套接字。 How can I tell client to close socket when server is disconnected from network? 当服务器与网络断开连接时,如何告诉客户端关闭套接字?
The reason it happens (if I understand the problem correctly) is that there is not inherent way to know that a connection has been closed, unless you try to send a package. 发生这种情况的原因(如果我正确理解了问题)是没有固有的方式知道连接已关闭,除非您尝试发送程序包。 So in your client, if you try to send an empty package over the connection, it will immediately report if the connection has been closed. 因此,在客户端中,如果您尝试通过连接发送空包,它将立即报告连接是否已关闭。
This is the reason that Heartbeats exist, and you can configure your socket to use them, or you can have your client periodically (or when needed) attempting to send an empty package and report the status of the connection. 这就是存在心跳的原因,您可以配置套接字以使用它们,或者可以让客户端定期(或在需要时)尝试发送空包并报告连接状态。
There is an excellent article on CodeProject about this, see here . 在CodeProject上有一篇关于此的出色文章, 请参见此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.