Raju Penumatsa Raju Penumatsa - 3 months ago 85
Java Question

Never ending of reading server response using jSch

I am trying to run commands at unix server by connecting through jSch0.1.49 library. I have gone through the samples provided by jSch and even http://sourceforge.net/apps/mediawiki/jsch/index.php?title=Official_examples

I am able to read the response from the server and printed it to console but the loop is *never endin*g. I doubt why the Channele is not closing once it is finished reading response from server.

while (true) {
while (inputStream.available() > 0) {
int i = inputStream.read(buffer, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(buffer, 0, i));//It is printing the response to console
}
System.out.println("done");// It is printing continuously infinite times

if (channel.isClosed()) {//It is never closed
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}

Answer

The channel does not close itself when there is no input left. Try closing it yourself after you have read all data.

while (true) {
    while (inputStream.available() > 0) {
        int i = inputStream.read(buffer, 0, 1024);
        if (i < 0) {
            break;
        }
        System.out.print(new String(buffer, 0, i));//It is printing the response to console
    }
    System.out.println("done");

    channel.close();  // this closes the jsch channel

    if (channel.isClosed()) {
        System.out.println("exit-status: " + channel.getExitStatus());
        break;
    }
    try{Thread.sleep(1000);}catch(Exception ee){}
}

The only time you are going to use a loop that doesnt manually close the channel is when you have interactive keyboard input from the user. Then when the user does an 'exit' that will change the channel's 'getExitStatus'. If your loop is while(channel.getExitStatus() == -1) then the loop will exit when the user has exited. You still need to disconnect the channel and session yourself after you detect an Exit Status.

It is not listed on their example page, but JSCH hosts an interactive keyboard demo on their site. http://www.jcraft.com/jsch/examples/UserAuthKI.java

Even their demo, which I used to connect to an AIX system without changing any of their code... does not close when you exit the shell!

I had to add the following code to get it to exit properly after I had typed 'exit' in my remote session:

     channel.connect();

     // My added code begins here
     while (channel.getExitStatus() == -1){
        try{Thread.sleep(1000);}catch(Exception e){System.out.println(e);}
     }

     channel.disconnect();
     session.disconnect();
     // My Added code ends here

   }
   catch(Exception e){
     System.out.println(e);
   }
}
Comments