Sample code for 30+ languages & platforms
JavaScript

Stop an SSH Tunnel Listener (StopAccepting)

See more SSH Tunnel Examples

Demonstrates the Chilkat SshTunnel.StopAccepting method, which stops the local listener so no new client connections are accepted. The only argument (waitForThread) selects whether to wait for the listener thread to exit. Existing forwarded clients remain connected.

Background: The distinction from CloseTunnel is the point: StopAccepting closes only the front door, leaving already-connected clients to finish their transfers undisturbed. That makes it the graceful way to drain a tunnel — stop taking new work, let existing work complete, then close — rather than cutting everyone off at once.
Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat v11.4.0 or greater.
JavaScript
var success = false;

//  Demonstrates the SshTunnel.StopAccepting method, which stops the local listener so that no new
//  client connections are accepted.  The only argument (waitForThread) selects whether to wait for
//  the listener thread to exit.  Existing forwarded clients remain connected.

var tunnel = new CkSshTunnel();

tunnel.DestHostname = "db.internal.example.com";
tunnel.DestPort = 5432;

var sshPort = 22;
success = tunnel.Connect("ssh.example.com",sshPort);
if (success == false) {
    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.
var password = "mySshPassword";

success = tunnel.AuthenticatePw("mySshLogin",password);
if (success == false) {
    console.log(tunnel.LastErrorText);
    return;
}

var listenPort = 1080;
success = tunnel.BeginAccepting(listenPort);
if (success == false) {
    console.log(tunnel.LastErrorText);
    return;
}

//  ... the tunnel runs for a while ...

//  Stop accepting NEW connections, but leave already-connected clients running.
var waitForThread = true;
success = tunnel.StopAccepting(waitForThread);
if (success == false) {
    console.log(tunnel.LastErrorText);
    return;
}

console.log("The listener has stopped; existing clients continue.");

var waitForThreadExit = true;
success = tunnel.CloseTunnel(waitForThreadExit);
if (success == false) {
    console.log(tunnel.LastErrorText);
    return;
}