[英]InputStream read() blocks when server returns no input
I am working on a program for Android, which connects to a server via SSH to get some data. 我正在为Android开发一个程序,该程序通过SSH连接到服务器以获取一些数据。
The problem is, in the event a command is sent to the server, that doesn't return anything (such as cat on an empty file), my program hangs, seemingly being blocked by in.read(). 问题是,如果命令发送到服务器时没有返回任何内容(例如,空文件上的cat),我的程序挂起,似乎被in.read()阻塞了。
I have a breakpoint on the the line 我在线路上有一个断点
if ((read = in.read(buffer)) != -1){
and on the then/else lines below it. 并在其下方的else / else线上。 If I debug it, the program breaks normally on the if-statement, but when I hit continue, the program just hangs again, and never makes it to the next breakpoint.
如果我对其进行调试,则该程序通常会在if语句中中断,但是当我单击继续时,该程序只会再次挂起,并且永远不会到达下一个断点。
The program works normally if it actually gets a response from the server, but I'd like to protect my program from a hang if the server isn't cooperating properly. 如果该程序实际上从服务器获得响应,则该程序可以正常工作,但是如果服务器不能正确合作,我想保护程序免受挂起。
I am using the J2SSH library. 我正在使用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;
}
Reading and writing should be done in separate threads. 读写应该在单独的线程中进行。 read() is a blocking method that waits until data is available from the server.
read()是一种阻塞方法,它等待直到服务器上的数据可用为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.