Server detecting a client losing connection from the socket

大兔子大兔子 提交于 2019-12-06 12:46:02

问题


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?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/6003580/server-detecting-a-client-losing-connection-from-the-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!