java – 使用jSch读取服务器响应永无止境
发布时间:2020-12-15 07:37:53 所属栏目:Java 来源:网络整理
导读:我试图通过连接jSch0.1.49库在unix服务器上运行命令.我已经浏览了jSch甚至 http://sourceforge.net/apps/mediawiki/jsch/index.php?title=Official_examples提供的样本 我能够从服务器读取响应并将其打印到控制台,但循环是*永远不会结束* g.我怀疑为什么Chan
|
我试图通过连接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,1024);
if (i < 0) {
break;
}
System.out.print(new String(buffer,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,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);
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
