开发者

Check availability of Internet Connection + Communicate between 2 threads

开发者 https://www.devze.com 2023-03-30 06:36 出处:网络
I have 2 questions: How can I check if Internet connection is whether turned on or turned off? I\'m using Html Unit and I\'m working on Windows.

I have 2 questions:

  1. How can I check if Internet connection is whether turned on or turned off? I'm using Html Unit and I'm working on Windows.

  2. I want to make a JLabel that states the availability of internet connection in my JFrame. Something like:

while(true)
{
    if(isOnline()) label.setText("online");
    else label.setText("offline");
}

but I think I need 2 sperated threads, but how could I create t开发者_Python百科hese 2 threads and communicate between them and achieve this?


A similar question was answered here: how-to-check-if-internet-connection-is-present-in-java

To do the second part of your question, I suppose you could call the InetAddress.isReachable method in a java.util.Timer that is wrapped in a SwingWorker thread to periodically poll the connection.


while (true) is a bit harsh on your resources, there should be a pause of ~10s in there. It's not like this would need to be as accurate and real-time as a stock price ticker.

With Swing, the rule is to do nothing that takes time on the event dispatch thread. Background tasks or other long-running operations should never run on it.

For your particular case this applies:

Programs whose GUI must be updated as the result of non-AWT events:

For example, suppose a server program can get requests from other programs that might be running on different machines. These requests can come at any time, and they result in one of the server's methods being invoked in some possibly unknown thread. How can that method update the GUI? By executing the GUI update code in the event-dispatching thread.

So what I would do is set up a scheduled task that checks for the availability of an internet connection every 10 seconds off the event-dispatch thread - this is probably best set up right away in your main method. The updating of the GUI on the other hand should then happen on the event dispatch thread. Here is a proposal for a Runnable that could do the update on your label. I'll explain the ConnectionCheckerlater. We execute it using a ExecutorService and set a timeout of 5 seconds. If the ConnectionChecker succeeds within 5 seconds, you are connected, otherwise you are not. This result is then used to update the JLabel on the event dispatch thread using SwingUtilities#invokeLater.

public static class Updater implements Runnable {
    private final JLabel label;
    private final ExecutorService executor;
     /* constructor left out */
    public void run() {
        boolean connected = false;
        Future<?> connHandle = executor.submit(new ConnectionChecker());
        try {
            connHandle.get(5, TimeUnit.SECONDS);
            connected = true;
        } catch (TimeOutException ex) {
            /* connected = false; */
        }
        catch (InterruptedException ex) {
            /* Let it be handled higher elsewhere */
            Thread.currentThread().interrupt();
        } catch (CancellationException ex) {
            /* happens only if you actively cancel the Future */
        } catch (ExecutionException ex) {
            /* connected = false */
        }

        final boolean result = connected;
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                if (result)
                    label.setText("online");
                else
                    label.setText("offline");
            }
        });
    }
}

Now we have to set up a periodically executed Updater in the main method, where we also create the JLabel and the ExecutorService:

public static void main(String... args) {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    JLabel label = ...;
    Updater updater = new Updater(label, executor);
    executor.scheduleAtFixedRate(updater, 0, 10, TimeUnit.SECONDS);
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //GUI initialization code
        }
    });
}

Finally, let's reason about ConnectionChecker. There's plenty of ways how you could do this. A quick and dirty solution is to simply fetch a web page that's likely to stay in the next few years - how about www.google.com. If you are connected to the Internet (correctly), this query will succeed. Otherwise, it will finally throw some Exception. With a connection, the download should be done in under 5 seconds - if it's not, then it's safe to time out the connection attempt. Either way, you will receive an Exception in your Updater if the download did not succeed in time. Use a simple URLConnection or similar for the download.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号