我正在開發一個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;
}
我認爲這是一個重複這個http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-java-inputstream-with-a-timeout – 2012-01-02 21:14:11