我有一个等待Runnable
连接的Socket
类。我想添加JButton
,这会导致它停止等待连接并退出循环。
这是循环
volatile boolean finished = false;
while (!finished) {
System.out.println("Server Started....");
clientSocket = serverSocket.accept(); // want to skip this line when the button is pressed
if (!clientSocket.isClosed() && ServerSettings.getServerStatus() != -1) {
// start communication
} else {
// close connection
}
}
我查找了这个问题,发现a solution here退出循环。但这并不能完全解决我的问题。我可以更改finished
变量的值,但要检查新值,我仍然需要跳过等待一次。
任何帮助都很明显。
答案 0 :(得分:0)
您可以调用close()方法。这将阻止连接的萎缩。
答案 1 :(得分:0)
而不是ServerSocket
,使用ServerSocketChannel
,它的accept()
方法不会阻止。来自文档:
public abstract SocketChannel accept() throws IOException
接受与此频道套接字的连接。
如果此通道处于非阻塞模式,则如果没有挂起的连接,此方法将立即返回null。