Android™
Android™
Close an SSH Tunnel (CloseTunnel)
See more SSH Tunnel Examples
Demonstrates the Chilkat SshTunnel.CloseTunnel method, which disconnects active tunnel clients and stops the tunnel-manager thread. The only argument (waitForThreads) selects whether to wait for the worker threads to exit.
Background: This is the full shutdown — it stops the listener, disconnects clients, and ends the background threads, so it is what you call when the tunnel is no longer needed. Passing
true for waitForThreads makes the call block until the workers have actually exited, which matters before the program terminates or reuses the object; if a worker fails to stop, the method returns false and LastErrorText explains why.Chilkat Android™ Downloads
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;
import android.app.Activity;
import com.chilkatsoft.*;
import android.widget.TextView;
import android.os.Bundle;
public class SimpleActivity extends Activity {
private static final String TAG = "Chilkat";
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean success = false;
// Demonstrates the SshTunnel.CloseTunnel method, which disconnects active tunnel clients and stops
// the tunnel-manager thread. The only argument (waitForThreads) selects whether to wait for the
// worker threads to exit.
CkSshTunnel tunnel = new CkSshTunnel();
tunnel.put_DestHostname("db.internal.example.com");
tunnel.put_DestPort(5432);
int sshPort = 22;
success = tunnel.Connect("ssh.example.com",sshPort);
if (success == false) {
Log.i(TAG, tunnel.lastErrorText());
return;
}
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
String password = "mySshPassword";
success = tunnel.AuthenticatePw("mySshLogin",password);
if (success == false) {
Log.i(TAG, tunnel.lastErrorText());
return;
}
int listenPort = 1080;
success = tunnel.BeginAccepting(listenPort);
if (success == false) {
Log.i(TAG, tunnel.lastErrorText());
return;
}
// ... the tunnel runs ...
// Shut everything down: disconnect clients and stop the tunnel-manager thread. With
// waitForThreads true, the method waits for the worker threads to exit.
boolean waitForThreads = true;
success = tunnel.CloseTunnel(waitForThreads);
if (success == false) {
Log.i(TAG, tunnel.lastErrorText());
return;
}
Log.i(TAG, "Tunnel closed.");
}
static {
System.loadLibrary("chilkat");
// Note: If the incorrect library name is passed to System.loadLibrary,
// then you will see the following error message at application startup:
//"The application <your-application-name> has stopped unexpectedly. Please try again."
}
}