服务器检测到客户端失去与套接字的连接
在 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)
相关文章