Sample code for 30+ languages & platforms
React Native

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 React Native Downloads

React Native
import { SshTunnel } from '@chilkat/react-native'

async function chilkatExample() {
  // 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.

  const tunnel = new SshTunnel();

  tunnel.destHostname = 'db.internal.example.com';
  tunnel.destPort = 5432;

  const sshPort = 22;
  try {
    await tunnel.connectAsync('ssh.example.com', sshPort);
  } catch {
    console.log(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.
  const password = 'mySshPassword';

  try {
    await tunnel.authenticatePwAsync('mySshLogin', password);
  } catch {
    console.log(tunnel.lastErrorText);
    return;
  }

  const listenPort = 1080;
  try {
    await tunnel.beginAcceptingAsync(listenPort);
  } catch {
    console.log(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.
  const waitForThreads = true;
  try {
    tunnel.closeTunnel(waitForThreads);
  } catch {
    console.log(tunnel.lastErrorText);
    return;
  }

  console.log('Tunnel closed.');
}