title: What to do when ServerSocket throws IOException and keeping server running
body: <p>Basically I want to create a rock solid server.</p>
  
  <pre><code>while (keepRunning.get()) {
      try {
          Socket clientSocket = serverSocket.accept();
  
          ... spawn a new thread to handle the client ...
      } catch (IOException e) {
          e.printStackTrace();
          // NOW WHAT?
      }
  }
  </code></pre>
  
  <p>In the IOException block, what to do? Is the Server socket at fault so it need to be recreated? For example wait a few seconds and then</p>
  
  <pre><code>serverSocket = ServerSocketFactory.getDefault().createServerSocket(MY_PORT);
  </code></pre>
  
  <p>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.</p>
  
  <p>EDIT: After some answers, here my attempt to deal with the IOException. Would the implementation be guaranteeing keeping the server up and only re-create server socket when only necessary?</p>
  
  <pre><code>while (keepRunning.get()) {
      try {
          Socket clientSocket = serverSocket.accept();
  
          ... spawn a new thread to handle the client ...
          bindExceptionCounter = 0;
      } catch (IOException e) {
          e.printStackTrace();
  
          recreateServerSocket();
      }
  }
  
  private void recreateServerSocket() {
      while (keepRunning) {
          try {
              logger.info("Try to re-create Server Socket");
              ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(RateTableServer.RATE_EVENT_SERVER_PORT);
  
              // No exception thrown, then use the new socket.
              serverSocket = socket;
              break;
          } catch (BindException e) {
              logger.info("BindException indicates that the server socket is still good.", e);
              bindExceptionCounter++;
  
              if (bindExceptionCounter &lt; 5) {
                  break;
              }
          } catch (IOException e) {
              logger.warn("Problem to re-create Server Socket", e);
              e.printStackTrace();
  
              try {
                  Thread.sleep(30000);
              } catch (InterruptedException ie) {
                  logger.warn(ie);
              }
          }
      }
  }    
  </code></pre>