在我的服务器应用程序中,我试图处理使用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();
发布于 2011-05-24 23:58:13
只需关闭ServerSocket,
并捕获结果SocketClosedException
即可。
并摆脱thread.stop()
。为什么,见Javadoc。
发布于 2011-05-24 23:37:45
我认为处理这一问题的一种常见方法是在循环中使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
}
}
然后,当您想关闭服务器时,只需将代码设置为“运行”为false,它就会关闭。
我希望这是合理的!
https://stackoverflow.com/questions/6120986
复制