Sample code for 30+ languages & platforms
Lua

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.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- 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.

local tunnel = chilkat.SshTunnel.new()

tunnel.dest_hostname = "db.internal.example.com"
tunnel.dest_port = 5432

local sshPort = 22
local success = tunnel:connect("ssh.example.com", sshPort)
if not success then
    print(tunnel.last_error_text)
    return
end

-- 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.
local password = "mySshPassword"

success = tunnel:authenticate_pw("mySshLogin", password)
if not success then
    print(tunnel.last_error_text)
    return
end

local listenPort = 1080
success = tunnel:begin_accepting(listenPort)
if not success then
    print(tunnel.last_error_text)
    return
end

-- ... the tunnel runs for a while ...

-- Stop accepting NEW connections, but leave already-connected clients running.
local waitForThread = true
success = tunnel:stop_accepting(waitForThread)
if not success then
    print(tunnel.last_error_text)
    return
end

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

local waitForThreadExit = true
success = tunnel:close_tunnel(waitForThreadExit)
if not success then
    print(tunnel.last_error_text)
    return
end