关闭监听ServerSocket

Vig*_*esh 3 java

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

  1. 启动服务器并等待连接。
  2. 停止与客户端连接的服务器。
  3. 停止正在等待客户端的服务器。

我可以启动服务器并使其在线程内等待客户端

socket = serverSocket.accept();
Run Code Online (Sandbox Code Playgroud)

我想要做的是我想手动关闭正在等待连接的套接字,我尝试过使用,

if (thread != null) {
     thread.stop();
     thread = null;
  }
  if (socket != null) {
     try {
        socket.close();
        socket = null;
     }
     catch (IOException e) {
        e.printStackTrace();
     }
  }
Run Code Online (Sandbox Code Playgroud)

执行上述代码后,即使套接字变为空,当我尝试从客户端连接到服务器时,连接就会建立,所以我的问题是如何中断在这里侦听连接的服务器套接字,

socket = serverSocket.accept();
Run Code Online (Sandbox Code Playgroud)

小智 5

我认为处理此问题的常见方法是使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
     }
}
Run Code Online (Sandbox Code Playgroud)

然后,当您想关闭服务器时,只需将代码将“正在运行”设置为 false,它就会关闭。

我希望这是有道理的!