Java Quickly check for network connection

前端 未结 4 1969
暗喜
暗喜 2021-02-20 08:14

My issue is fairly straightforward. My program requires immediate notification if a network connection is lost. I\'m using Java 5, so I\'m unable to use the very handy feature

4条回答
  •  野性不改
    2021-02-20 08:53

    My program requires immediate notification if a network connection is lost.

    Bad luck. You can't get an immediate notification with TCP/IP. It is full of buffering and retries and timeouts, so it doesn't do anything immediately, and TCP by design doesn't have anything corresponding to a 'dial tone', nor any API. The only way to detect a lost connection is to try to do I/O over it.

    I'm using Java 5, so I'm unable to use the very handy features of NetworkInterface.

    They won't help you either. All they can tell you is whether an NIC is up or down, nothing about the state of your connectedness to the wider world.

    URL url = new URL("http://www.google.com");
    HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
    // trying to retrieve data from the source. If offline, this line will fail:
    Object objData = urlConnect.getContent();
    return true;
    

    That will timeout with a DNS failure if you're offline.

    Socket socket = new Socket("www.google.com", 80);
    netAccess = socket.isConnected();
    socket.close();
    return netAccess;
    

    Ditto. However even if it didn't, socket.isConnected() would always return true. Those APIs like isConnected(), isBound(), isClosed(), only tell you what you have done to the socket. They don't tell you anything about the state of the connection. They can't, for the reason I gave above.

    And you forgot to close the socket in the case of an exception, so you have a resource leak.

    I need a method that will return immediately.

    Impossible for the reasons given. You need to redesign around the realization that this function doesn't exist.

提交回复
热议问题