2013-04-05 35 views
3

我正在使用Java套接字進行ping程序。我的程序中的一個錯誤是,有時它不會連接,只會永遠坐在那裏。所以我試圖添加一個超時(二十秒後),ping會失敗。但我不知道如何。Java - 如何測量超時

這裏是我的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塊的開始處或者代碼中的其他地方測量二十秒鐘的任何建議,以便在ping過程中不會卡住?

+0

線程框架有這個非常好的設施。 – jn1kk 2013-04-05 20:20:53

+1

您可以在單獨的線程中執行ping命令並使用[Thread.join()](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join(long) )給它一些時間來完成。 – jahroy 2013-04-05 20:21:02

+1

@jahroy - 嗯...你能告訴我一個例子嗎? – 0101011 2013-04-05 20:29:27

回答

1

由於「jsn」和「jahory」表示您需要使用線程完成此操作。這裏有2個有用的鏈接,你可以檢查它們;)

+0

我已經看到了一個線程的行爲,它將所有東西堵塞,直到完成。這會做同樣的事嗎? – 0101011 2013-04-05 20:32:36

+1

線程的要點在於,當線程並行工作時,您的程序可以繼續執行......所以線程應該在「_everything卡住了」的情況下提供解決方案。 – jahroy 2013-04-05 21:01:25

+0

謝謝,線程真的幫了我! – 0101011 2013-04-06 02:44:30

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 
    } 
    } 
+1

嗯....看起來有點像一個計時器,我會嘗試一下... – 0101011 2013-04-05 20:38:40