1

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));
  }
}
4

2 回答 2

1

2x 入口点,一种形式捕获:永远不会结束。

  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....");
  }
于 2013-05-10T10:58:56.763 回答
1

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

不,它没有。ServerSockets永远得不到EOFExceptions。相反,您接受Sockets的一个是得到一个EOFException,这只是意料之中的,并且您正在关闭正确SocketServerSocket不正确的 。已接受套接字的异常不会影响侦听套接字。

于 2013-05-10T12:38:18.913 回答