2012-01-02 14 views
0

我正在開發一個Android程序,它通過SSH連接到服務器以獲取一些數據。當服務器返回沒​​有輸入時,InputStream read()塊被阻止

問題是,如果一個命令發送到服務器,它不會返回任何東西(如空文件上的貓),我的程序掛起,看起來被in.read()阻塞。

我對行

if ((read = in.read(buffer)) != -1){ 

,並在它下面的那麼/其他線路斷點。如果我調試它,程序會在if語句中正常斷開,但是當我繼續時,程序再次掛起,並且永遠不會進入下一個斷點。

如果程序實際上從服務器獲取響應,程序將正常工作,但如果服務器沒有正確協作,我想保護程序免於掛起。

我正在使用J2SSH庫。

public String command(String command) { 
    command = command + "\n"; 

    if (session.getSessionType().equals("Uninitialized") || session.isClosed()) { 
     openShell(); 
    } 

    OutputStream out = session.getOutputStream(); 
    InputStream in = session.getInputStream(); 


    byte buffer[] = new byte[255]; 
    int read; 
    String in1 = null; 
    String fullOutput = ""; 

    try { 
     try { 
      out.write(command.getBytes()); 
     } catch (IOException e){ 
      Log.e(TAG,"Error writing IO stream"); 
      e.printStackTrace(); 
     } 
     boolean retrivingdata = true; 
     while (retrivingdata){ 
      String iStreamAvail = "Input Stream Available "+ in.available(); 

      if ((read = in.read(buffer)) != -1){ 
       retrivingdata = true; 
      } else { 
       retrivingdata = false; 
       return null; 
      } 

      in1 = new String(buffer, 0, read); 
      fullOutput = fullOutput + in1; 

      if (read < 255){ 
       break; 
      } 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return fullOutput; 
} 
+0

我認爲這是一個重複這個http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-java-inputstream-with-a-timeout – 2012-01-02 21:14:11

回答

0

閱讀和寫作應該在不同的線程中完成。 read()是一個阻塞方法,一直等到數據從服務器可用時爲止。

+0

即使我跑它在一個單獨的線程中,該線程將永遠持續等待響應。 – coreno 2012-01-10 19:52:45

+0

這就是套接字的工作原理。你也可以看看下面的套接字選項,如果你想在超時後解鎖你的話:http://developer.android.com/reference/java/net/SocketOptions.html#SO_TIMEOUT – clemp6r 2012-01-11 08:26:57

相關問題