[英]Is there a proper way to detect and handle sudden disconnected server
I'm using this code to detect if a server isn't connect我正在使用此代码来检测服务器是否未连接
private boolean isServerListening() {
try {
s = new Socket("localhost", PORT);
return true;
} catch (IOException e) {
System.out.println(e);
return false;
}
}
and Thread to handle suddenly disconnected server和线程来处理突然断开的服务器
Thread checkServer = new Thread(() -> {
while (true) {
if (isServerListening()==false) {
JOptionPane.showMessageDialog(null, "Server is disconnected!");
System.exit(0);
}
}
});
The problem is:问题是:
Thread
still show the JOptionPane
and terminate my program.Am I wrong at some point?Thread
仍然显示JOptionPane
并终止我的程序。我在某些时候错了吗?There is no general solution that fits all.没有适合所有人的通用解决方案。 Bsically there are different types of "lost connection":
基本上有不同类型的“丢失连接”:
The Socket
has the methods isConnected() and isClosed() which you should use. Socket
具有您应该使用的方法 isConnected() 和 isClosed() 。
The only way to check a connection surely is by sending a message and receiving an answer.确定检查连接的唯一方法是发送消息并接收答复。 Then it might take up to 60 seconds (by default) until your computer notices the lost connection.
然后最多可能需要 60 秒(默认情况下),直到您的计算机注意到连接丢失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.