IOException后重新启动ServerSocket

时间:2013-05-10 10:46:52

标签: java serversocket ioexception

如何在ServerSocket之后重启IOException

我的服务器套接字有时会获得EOFException,然后停止接受新连接。为了解决这个问题,我尝试关闭旧的服务器套接字并在抛出异常后创建一个新的服务器套接字。但是,即使在创建新服务器套接字之后,也不接受新连接。有人可以理解为什么这不起作用吗?

public Server() throws IOException {        
  try {
    listen(port);
  }
  catch (IOException e) {
    System.out.println("Server() - IO exception");
    System.out.println(e);

    /*when an exception is caught I close the server socket and try opening it a new one */
    serverSocket.close();

    listen(port);
  }
}

private void listen(int port) throws IOException {
  serverIsListening = true;

  serverSocket = new ServerSocket(port);
  System.out.println("<Listening> Port: " + serverSocket);

  while (serverIsListening) {
    if (eofExceptionThrown){  //manually triggering an exception to troubleshoot
      serverIsListening = false;
      throw new EOFException();
    }

    //accept the next incoming connection
    Socket socket = serverSocket.accept();
    System.out.println("[New Conn] " + socket);

    ObjectOutputStream oOut = new ObjectOutputStream(socket.getOutputStream());

    // Save the streams
    socketToOutputStreams.put(socket, oOut);

    // Create a new thread for this connection, and put it in the hash table
    socketToServerThread.put(socket, new ServerThread(this, socket));
  }
}

2 个答案:

答案 0 :(得分:1)

2x入口点,一个表单catch:永远不会结束。

  try {
    listen(port);
  }
  catch (IOException e) {
    System.out.println("Server() - IO exception");
    System.out.println(e);

    /*when an exception is caught I close the server socket and try opening it a new one */
    serverSocket.close();

    listen(port);
  }

我会在循环中做,而布尔值为真:

while(needToListen){
  try{
     listen(port)
   }catch(Exception ex){
     if(exception   is what needed to break the loop, like a message has a string on it){
       break;
     }
   }
}

  if(needToListen){
      Log.e("something unexpected, unrecoverable....");
  }

答案 1 :(得分:1)

  

我的服务器套接字有时会获得EOFException,然后停止接受新连接

不,不。 ServerSockets永远不会获得EOFExceptions。相反,您接受的Sockets之一正在获得EOFException,这只是预期的结果,您正在关闭Socket,这是正确的, ServerSocket,这是不正确的。接受的套接字上的异常不会影响侦听套接字。