[英]How can i keep a Jsch Session alive on android
我正在編寫一個通過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)嘗試過,但是沒有用。 是否有保持會話和頻道有效的可能性? 我已經看到了該用戶的解決方案,但這對我來說不起作用,因為服務器與服務之間的連接始終保持連接很重要。
pwd
。 盡管您可能需要解釋,但是為什么打開“ shell”會話卻看起來很可疑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.