Java Quickly check for network connection

前端 未结 4 1946
暗喜
暗喜 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:33

    You need to first create an interface called NetworkListener, for example

    public interface NetworkListener {
        public void sendNetworkStatus(String status);
    }
    

    Next, create a class and call it NetworkStatusThread, for example

    public class NetworkStatusThread implements Runnable {
        List listenerList = new Vector();
    
        @SuppressWarnings("unchecked")
        public synchronized void addNetworkListener(NetworkListener nl) {
            listenerList.add(nl);
        }
    
        public synchronized void removeNetworkListener(NetworkListener nl) {
            listenerList.remove(nl);
        }
    
    
        private synchronized void sendNetworkStatus(String status) {
            // send it to subscribers
            @SuppressWarnings("rawtypes")
            ListIterator iterator = listenerList.listIterator();
            while (iterator.hasNext()) {
                NetworkListener rl = (NetworkListener)iterator.next();
                rl.sendNetworkStatus(status);
            }
        }
    
        public void run() {
            while (true) {
            System.out.println("Getting resource status");
            try {
                 Thread.sleep(2000);
                 System.out.println("Sending resource status to registered listeners");
                 this.sendResourceStatus("OK");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
     }
    

    Then in your class that instantiates the Thread, do this:

    NetworkStatusThread netStatus = new NetworkStatusThread();
    netStatus.addNetworkListener(this);
    Thread t = new Thread(netStatus);
    t.Start();
    

    Also, in that class, you need to implement the NetworkListener, in order to get the callbacks.

    In your run() method above, you can implement the code by @Ali, but pass my status:

      int timeout = 2000;
      InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
      for (InetAddress address : addresses) {
        if (address.isReachable(timeout))
           this.sendResourceStatus("OK");
        else
           this.sendResourceStatus("BAD");
      }
    

提交回复
热议问题