3

我正在使用 Java 套接字制作一个 ping 程序。我的程序中的一个错误是有时它无法连接并且会永远坐在那里。所以我试图添加一个超时(二十秒后),ping 将失败。但我不知道该怎么做。

这是我的 ping 程序的一部分:

boolean result = false;
long before1 = System.nanoTime();
out.println(new byte[64]);
System.out.println("(1) Sent 64 bytes of data to " + address
                    + "...");
try {
    if ((in.readLine()) != null) {
        int size = in.readLine().toString().getBytes().length;
        long after = System.nanoTime();
        long s = ((after - before1) / 1000000L) / 1000;
        System.out.println("(1) Recieved reply from " + address
            + " (" + size + " bytes), time = " + s
                + " seconds...");
        result = true;
    } else if ((in.readLine()) == null) {
        long after = System.nanoTime();
        long s = ((after - before1) / 1000000L) / 1000;
        System.out.println("(1) Failed to recieve reply from "
            + address + ", time = " + s + " seconds...");
            result = false;
    }

} catch (IOException exc) {

    long after = System.nanoTime();
    long s = ((after - before1) / 1000000L) / 1000;
    System.err.println("(1) Failed to recieve reply from "
        + address + ", time = " + s + " seconds...\nReason: "
                        + exc);
    result = false;

}

但是我想在我的代码中的任何地方测量经过的时间,而不是:

long time = System.nanoTime();

如果我的代码的一部分卡在做某事,它将在 20 秒后超时。
关于如何测量是否在 try/catch 块开始或我的代码中的其他任何地方已经过去了 20 秒的任何建议,因此它不会在 ping 期间卡住?

4

3 回答 3

1

正如“jsn”和“jahory”所说,您需要使用线程来执行此操作。这是 2 个有用的链接,您可以查看它们;)

于 2013-04-05T20:29:09.140 回答
1

您可以使用FutureFutureTask

   ExecutorService pingExecutor = ... // executor service to run the ping in other thread

   void showPing(final String target) throws InterruptedException {

     Future<String> ping = executor.submit(new Callable<String>() {
         public String call() {
             String pingResult = ... // do your Ping stuff
             return pingResult;
         }});

     System.out.println("Pinging..."); // do other things while searching

     try {
       System.out.println(future.get(20, TimeUnit.SECONDS)); // use future, waits 20 seconds for the task to complete
     } catch (ExecutionException ex) {
     } catch (TimeoutException tex) {
       // Ping timed out
     }
   }
于 2013-04-05T20:36:12.107 回答
0

你可以在这里找到一些提示:How do I call some blocking method with timeout in Java?

未来的界面看起来是解决您问题的好方法。但是请记住,根据您的任务正在做什么,您可能无法真正取消它。附加信息:

于 2013-04-05T20:40:08.370 回答