在Java中,如果我通过套接字将客户端连接到服务器并且客户端有异常导致它崩溃,那么服务器是否有任何方法可以检测到套接字连接丢失。
In Java, if I connect to a client to a server via a socket and the client has an exception which causes it to crash, is there any way the server can detect that the socket connection is lost.
我假设一种方法会对客户端进行某种心跳轮询,但是有更简单/更简单的方法吗?
I assume one method would be have some sort of heartbeat polling the client, but is there a simpler/easier way?
推荐答案有几种方法,取决于你认为是崩溃。
There are a few ways, depending on what you consider to be a "crash".
如果客户端进程死亡,客户端进程操作系统将关闭套接字。服务器可以通过执行 read()来检测到这一点,它将返回-1(EOF)或引发 SocketException (连接重置)。
If the client process dies, the client OS will close the socket. The server can detect this by performing a read(), which will either return -1 (EOF) or raise a SocketException ("connection reset").
如果客户端进入无限循环,连接将保持打开状态;检测到这种情况的唯一方法是在协议中加入某种心跳。
If the client gets into an infinite loop, the connection will remain open; the only way to detect this is by incorporating some kind of "heartbeat" into your protocol.
如果重新启动客户端主机或网络连接断开,服务器可能不会通知,除非:
If the client host is rebooted or the network connection breaks, the server may not notice unless either:
- 协议具有上述心跳机制,有某种超时或
- 通过调用 socket.setKeepAlive(true)在套接字上启用TCP keepalive - 这指示操作系统定期*发送数据包以检查远程端连接是否存活,如果没有关闭连接
- the protocol has a "heartbeat" mechanism as above, with some kind of timeout, or
- TCP keepalive is enabled on the socket by calling socket.setKeepAlive(true) - this instructs the OS to periodically* send a packet to check that the remote end of the connection is alive, closing the connection if not
* Windows和Linux默认为2小时;您可以更改此系统范围,但不能更改每个插槽(在Java下,无论如何)
*both Windows and Linux default to 2 hours; you can change this system-wide but not per-socket (under Java, anyway)
更多推荐
服务器检测到客户端从套接字丢失连接
发布评论