我正在使用此代码来检测服务器是否未连接
private boolean isServerListening() {
try {
s = new Socket("localhost", PORT);
return true;
} catch (IOException e) {
System.out.println(e);
return false;
}
}
和用于处理突然断开的服务器的线程
Thread checkServer = new Thread(() -> {
while (true) {
if (isServerListening()==false) {
JOptionPane.showMessageDialog(null, "Server is disconnected!");
System.exit(0);
}
}
});
问题是:
Thread
仍显示JOptionPane
并终止我的程序。我在某个时候错了吗? 没有适合所有情况的通用解决方案。基本上有不同类型的“丢失的连接”:
Socket
具有应使用的方法isConnected()和isClosed()。
唯一确定连接的方法是通过发送消息并接收答案。然后,可能最多需要60秒(默认情况下),您的计算机才会注意到丢失的连接。