2010-05-18 95 views
3

有沒有簡單的方法可以跳過java中的readLine()方法,如果它需要比2秒更長的時間?在java中跳過BufferedReader的readLine()方法

這裏的語境中,我要問這樣一個問題:

public void run() 
{ 
    boolean looping = true; 
    while(looping) { 
     for(int x = 0; x<clientList.size(); x++) { 
      try { 
       Comm s = clientList.get(x); 
       String str = s.recieve(); 
       // code that does something based on the string in the line above 
      } 
      // other stuff like catch methods 
     } 
    } 
} 

通訊是一類我寫的,和接收方法,其中包含一個名爲「在」的BufferedReader,是這樣的:

public String recieve() 
{ 
    try { if(active) return in.readLine(); } 
    catch(Exception e) { System.out.println("Comm Error 2: "+e); } 
    return ""; 
} 

我注意到程序停止並且在繼續之前等待輸入流有東西要讀。這是不好的,因爲我需要程序保持循環(當它循環時,它會發送到所有其他客戶端並要求輸入)。如果沒有東西可讀,是否有辦法跳過readLine()過程?

我也很確定我沒有解釋得很好,所以如果我感到困惑,請問我問題。

回答

4

超時本身並不是一個好主意。每個客戶端使用一個線程(或使用異步I/O,但除非您構建一些高性能應用程序,這是不必要的複雜)。

至於超時本身,它必須在封裝的流上完成。例如參見How can I set a timeout against a BufferedReader based upon a URLConnection in Java?

+0

在超時的底層Reader/Stream上使用'BufferedReader'或'BufferedInputStream'也是危險的。這些緩衝類不會嘗試從超時恢復,因此可能會丟失部分傳輸的數據包。 – 2010-05-19 00:28:08

相關問題