【问题标题】:Restart ServerSocket after IOExceptionIOException 后重启 ServerSocket
【发布时间】:2023-09-02 00:48:02
【问题描述】:

IOException之后如何重启ServerSocket

我的服务器套接字有时会收到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));
  }
}

【问题讨论】:

  • 你为什么决定新的连接不接受?是否抛出了一些异常?或者你不能创建新的套接字?还是只是忽略新客户?
  • 当我在抛出异常并且服务器忽略它之后连接新客户端时,即它不打印[New Conn]消息。
  • 我可能错了,因为我不确定。但您可以检查您是否手动触发了 EOF 异常。但是在您的 Server() 代码中,您正在捕获 IOException。确定,如果它有相同的效果。
  • 对不起,应该提到EOFException继承IOException

标签: java serversocket ioexception


【解决方案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....");
  }

【讨论】:

  • 我添加了一个嵌套的try catch 来覆盖对listen() 的第二次调用。似乎问题在于EOFException 第二次被抛出。解决方案是在再次调用listen() 之前将eofExceptionThrown 设置为false。您的回答让我明白了这一点,所以我将您标记为正确,谢谢。
【解决方案2】:

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

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

【讨论】: