How do you handle Socket Disconnecting in Java?

Hey all. I have a server written in java using the ServerSocket and Socket classes.

I want to be able to detect and handle disconnects, and then reconnect a new client if necessary.

What is the proper procedure to detect client disconnections, close the socket, and then accept new clients?


Presumably, you're reading from the socket, perhaps using a wrapper over the input stream, such as a BufferedReader. In this case, you can detect the end-of-stream when the corresponding read operation returns -1 (for raw read() calls), or null (for readLine() calls).

Certain operations will cause a SocketException when performed on a closed socket, which you will also need to deal with appropriately.


检测另一端的唯一安全方法是定期发送心跳信号,并根据缺少心跳信号将另一端设置为超时。


Is it just me, or has nobody noticed that the JavaDoc states a method under ServerSocket api, which allows us to obtain a boolean based on the closed state of the serversocket?

you can just loop every few seconds to check the state of it:

if(!serverSocket.isClosed()){
  // whatever you want to do if the serverSocket is connected
}else{
  // treat a disconnected serverSocket
}

EDIT: Just reading your question again, it seems that you require the server to just continually search for connections and if the client disconnects, it should be able to re-detect when the client attempts to re-connect. should'nt that just be your solution in the first place?

Have a server that is listening, once it picks up a client connection, it should pass it to a worker thread object and launch it to operate asynchronously. Then the server can just loop back to listening for new connections. If the client disconnects, the launched thread should die and when it reconnects, a new thread is launched again to handle the new connection.

Jenkov provides a great example of this implementation.

链接地址: http://www.djcxy.com/p/9688.html

上一篇: Android:DataOutputStream不会抛出Exception

下一篇: 你如何处理Java中的Socket断开连接?