【发布时间】:2018-10-03 21:53:31
【问题描述】:
我正在编写一个通过 SSH 连接到服务器的应用程序。我的目的是为应用程序的用户提供互联网连接,只要他们连接到服务器(SSH 脚本作为 Android 服务运行)。问题是,当我开始一个会话并创建一个频道时,一切正常。但大约 20-30 分钟(有时长达几个小时)后,频道和会话关闭。
连接函数:
public String connecting(
String username,
final String password,
String hostname,
int port) {
try {
Log.d("MainActivity", "Start JSch session and connect");
jsch = new JSch();
session = jsch.getSession(username, hostname, port);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
session.setServerAliveInterval(15);
session.setServerAliveCountMax(100);
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
InputStream in = channel.getInputStream();
serviceStatus = true;
streamtext = "";
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
streamtext = new String(tmp, 0, i);
}
}
if (channel.isClosed()) {
if (in.available() > 0) continue;
Log.d(TAG, "exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
ee.printStackTrace();
}
}
return streamtext;
} catch (Exception except){
except.printStackTrace();
passErrorToActivity("Error: Connection error");
return "Error: Connection error";
}
}
启动函数:
public void start(){
try {
new AsyncTask<Integer, Void, Void>() {
@Override
protected Void doInBackground(Integer... params) {
try {
passMessageToActivity(connecting(user, password, host, port));
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}.execute(1);
} catch (Exception exc) {
exc.printStackTrace();
}
"passMessageToActivity" 只是创建一个意图并将“streamtext”发送到 MainActivity
我已经用Session#setServerAliveInterval(int milliseconds) 尝试过,但是没有用。是否有可能保持会话和频道处于活动状态? 我已经看到了解决方案 of this user 但这对我不起作用,因为服务器和服务之间的连接始终处于正常状态很重要。
【问题讨论】:
标签: java android android-studio ssh jsch