gpt4 book ai didi

java - 使用 jSch 读取服务器响应永无止境

转载 作者:行者123 更新时间:2023-12-02 00:40:27 25 4
gpt4 key购买 nike

我正在尝试通过 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){}
}

最佳答案

当没有剩余输入时, channel 不会自行关闭。读取所有数据后尝试自行关闭它。

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

只有当您有来自用户的交互式键盘输入时,您才会使用不手动关闭 channel 的循环。然后,当用户执行“退出”时,将更改 channel 的“getExitStatus”。如果你的循环是 while(channel.getExitStatus() == -1) 那么循环将在用户退出时退出。 检测到退出状态后,您仍然需要自行断开 channel 和 session

它没有在他们的示例页面上列出,但 JSCH 在他们的网站上托管了一个交互式键盘演示。 http://www.jcraft.com/jsch/examples/UserAuthKI.java

即使是他们的演示,我用来连接到 AIX 系统而不更改任何代码...当您退出 shell 时也不会关闭!

在远程 session 中输入“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 读取服务器响应永无止境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16298279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com