What to do when ServerSocket throws IOException and keeping server running

前端 未结 4 1975
一整个雨季
一整个雨季 2021-02-10 08:21

Basically I want to create a rock solid server.

while (keepRunning.get()) {
    try {
        Socket clientSocket = serverSocket.accept();

        ... spawn a n         


        
相关标签:
4条回答
  • 2021-02-10 09:08

    If in doubt, you could try re-creating the server socket, using the same port. If the socket has been closed, then the creation will succeed and you can continue processing new connections. The old connections are gone, but that's outside of your control since the socket was closed. If the socket was not closed, then creating a new instance will fail since the port is still in use, which you can just ignore - i.e. don't replace the current server socket reference.

    In general, clients should also assume that connections will be broken and that reconnection is necessary. In other words, it's not just the server that has to be robust - clients should also anticipate connection errors and reconnect.

    0 讨论(0)
  • 2021-02-10 09:08

    Make sure you differentiate between different IOExceptions you might receive. Is it an exception on creating a connection? Is it an exception once a connection has already been established?

    The only code you gave is for accept()ing. Generally speaking, an IOException usually means an error on any layer on the physical network.

    Probably the best fallback behavior you can implement is to wait for a certain time quantum, and then try to reconnect. Assume you most possibly will not be able to reconnect, since you have lost network connection for more than a temporary period. Make sure you handle this gracefully. As @mdma mentioned, this must be supported by your clients as well.

    0 讨论(0)
  • 2021-02-10 09:09

    However if the server socket is still OK, then it is a pity to close it and kill all previously accepted connections that are still communicating.

    Please note that closing the server socket will NOT close previously accepted connections. As soon as a connection has been accepted it lives a separate, joyful life at a different port.

    0 讨论(0)
  • 2021-02-10 09:16

    You can get an IOException on an accept() if the server socket is closed (by you) or you run out of resources, e.g. file handles. Either way, there is not much you can do about it. If the serverSocket is closed (you can test for this) you probably had a good reason to do this. If you run out of resources, you will either have to increase your resource limit, which requires a restart of your application, or you have a resource leak.

    0 讨论(0)
提交回复
热议问题