Java 关闭侦听服务器套接字

Java 关闭侦听服务器套接字,java,Java,在我的服务器应用程序中,我试图处理使用ServerSocket的服务器,比如 启动服务器并等待连接 停止与客户端连接的服务器 停止正在等待客户端的服务器 我可以启动服务器,让它在线程内使用 socket = serverSocket.accept(); 我要做的是手动关闭等待连接的套接字,我已经尝试使用 if (thread != null) { thread.stop(); thread = null; } if (socket != null) { t

在我的服务器应用程序中,我试图处理使用ServerSocket的服务器,比如

  • 启动服务器并等待连接
  • 停止与客户端连接的服务器
  • 停止正在等待客户端的服务器
  • 我可以启动服务器,让它在线程内使用

    socket = serverSocket.accept();
    
    我要做的是手动关闭等待连接的套接字,我已经尝试使用

    if (thread != null) {
         thread.stop();
         thread = null;
      }
      if (socket != null) {
         try {
            socket.close();
            socket = null;
         }
         catch (IOException e) {
            e.printStackTrace();
         }
      }
    
    执行上述代码后,即使套接字变为null,当我尝试从客户端连接到服务器时,连接也会建立起来,所以我的问题是如何中断正在侦听连接的serversocket

    socket = serverSocket.accept();
    

    我认为一种常见的处理方法是在循环中使accept()调用超时

    比如:

    ServerSocket server = new ServerSocket();
    server.setSoTimeout(1000); // 1 second, could change to whatever you like
    
    while (running) { // running would be a member variable
         try {
             server.accept(); // handle the connection here
         }
         catch (SocketTimeoutException e) {
              // You don't really need to handle this
         }
    }
    
    然后,当您想关闭服务器时,只需将代码“running”设置为false,它就会关闭


    我希望这是有意义的

    只需关闭
    ServerSocket,
    并捕获结果
    SocketClosedException


    然后去掉
    线程.stop()
    。为什么

    Hi Phill Sacre,事实上我不想设定时间限制,我想让用户在他/她想要的时候控制启动和停止,无论它是在监听还是连接到客户,这是可能的。Hi Phill Sacre,我尝试了你的建议,我在1分钟后修复了60000毫秒,我得到了SocketTimeoutException,但仍然在那之后,客户端可以在特定的套接字上与服务器连接,知道吗?@Vignesh,因为您还没有关闭ServerSocket。正如EJP所建议的,除非关闭ServerSocket,否则这不是一个解决方案。没有
    SocketClosedException
    ,只有
    java.net.SocketException:socketclosed