How do you handle Socket Disconnecting in Java?

后端 未结 3 2027
暖寄归人
暖寄归人 2020-12-06 16:53

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 cl

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 17:28

    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.

提交回复
热议问题