0

我正在为 Android 开发一个程序,该程序通过 SSH 连接到服务器以获取一些数据。

问题是,如果一个命令被发送到服务器,它不返回任何东西(例如空文件上的 cat),我的程序挂起,似乎被 in.read() 阻止。

我在线上有一个断点

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

并在其下方的 then/else 行上。如果我调试它,程序会在 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;
}
4

1 回答 1

0

读和写应该在不同的线程中完成。read() 是一种阻塞方法,它一直等到服务器提供数据。

于 2012-01-03T13:13:00.573 回答