0

I am working on a program for Android, which connects to a server via SSH to get some data.

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().

I have a breakpoint on the the line

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

and on the then/else lines below it. 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.

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.

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;
}
coreno
  • 445
  • 1
  • 3
  • 14
  • I think that's a dup of this http://stackoverflow.com/questions/804951/is-it-possible-to-read-from-a-java-inputstream-with-a-timeout – Francis Upton IV Jan 02 '12 at 21:14

1 Answers1

0

Reading and writing should be done in separate threads. read() is a blocking method that waits until data is available from the server.

clemp6r
  • 3,665
  • 2
  • 26
  • 31
  • 1
    Even if I run it in a separate thread, that thread will just go on forever waiting for a response. – coreno Jan 10 '12 at 19:52
  • That's how sockets work. Also you may take a look at the following socket option if you want to unlock your threak after a timeout: http://developer.android.com/reference/java/net/SocketOptions.html#SO_TIMEOUT – clemp6r Jan 11 '12 at 08:26