简体   繁体   English

是否有适当的方法来检测和处理突然断开连接的服务器

[英]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:问题是:

  1. I think the method took too much time (about 4 seconds) to execute and return.So is there a proper way?我认为该方法执行和返回花费了太多时间(大约4秒)。那么有没有合适的方法?
  2. No matter the server is connected or not, this 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":基本上有不同类型的“丢失连接”:

  1. Your computer disconnects, so it knows immediatley that the connection is closed.您的计算机断开连接,因此它立即知道连接已关闭。
  2. The other side disconnects, it might happen that this signal does not reach your computer, so it will still think that you are connected.另一端断线,可能会发生这个信号没有到达你的电脑,所以它仍然会认为你已经连接上了。
  3. The physical connection breaks, both sides cannot inform the other side.物理连接中断,双方无法通知对方。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM