+-
java – 使用jSch读取服务器响应永无止境
我试图通过连接jSch0.1.49库在unix服务器上运行命令.我已经浏览了jSch甚至 http://sourceforge.net/apps/mediawiki/jsch/index.php?title=Official_examples提供的样本

我能够从服务器读取响应并将其打印到控制台,但循环是*永远不会结束* g.我怀疑为什么Channele一旦完成读取服务器的响应就不会关闭.

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){}
}
最佳答案
没有输入时,通道不会自行关闭.阅读完所有数据后,请尝试自行关闭它.

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){}
}

当您从用户输入交互式键盘时,您唯一一次使用不会手动关闭通道的循环.然后,当用户执行“退出”时,将更改频道的’getExitStatus’.如果你的循环是while(channel.getExitStatus()== -1),那么当用户退出时循环将退出.检测到退出状态后,您仍需要自行断开通道和会话.

它未在其示例页面上列出,但JSCH在其站点上托管了交互式键盘演示. http://www.jcraft.com/jsch/examples/UserAuthKI.java

甚至他们的演示,我曾经连接到AIX系统而不改变他们的任何代码…当你退出shell时它不会关闭!

在我的远程会话中键入“exit”后,我必须添加以下代码才能使其正常退出:

     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);
   }
}
点击查看更多相关文章

转载注明原文:java – 使用jSch读取服务器响应永无止境 - 乐贴网