开发者

Server detecting a client losing connection from the socket

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 s开发者_Go百科erver 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".

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:

  • 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

*both Windows and Linux default to 2 hours; you can change this system-wide but not per-socket (under Java, anyway)


TCP sockets do this anyway, and Java exposes it to the developer. See setKeepAlive() / getKeepAlive() in the Socket class. If a TCP message isn't sent from the client to the server for a certain period of time, the socket will close, and the server can remove the session information because it still has its endpoint.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜