在我的服务器应用程序中,我正在尝试处理使用 ServerSocket 的服务器,
- 启动服务器并等待连接。
- 停止与客户端连接的服务器。
- 停止正在等待客户端的服务器。
我可以启动服务器并让它在线程内等待客户端使用
socket = serverSocket.accept();
我想做的是我想手动关闭正在等待连接的套接字,我试过使用,
if (thread != null) {
thread.stop();
thread = null;
}
if (socket != null) {
try {
socket.close();
socket = null;
}
catch (IOException e) {
e.printStackTrace();
}
}
执行上面的代码后,即使套接字变为空,当我尝试从客户端连接到服务器时,连接已经建立,所以我的问题是如何中断监听这里连接的服务器套接字,
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,它就会关闭。
我希望这是有道理的!
关于java - 关闭监听ServerSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6120986/