Skip to content

Instantly share code, notes, and snippets.

@andykent
Created July 3, 2010 17:39
Show Gist options
  • Save andykent/462720 to your computer and use it in GitHub Desktop.
Save andykent/462720 to your computer and use it in GitHub Desktop.
Super simple, round robin, TCP port forwarding with node.js
net: require "net"
sys: require "sys"
LISTEN_PORT: 10000
SERVER_ADDRESS: '127.0.0.1'
AVAILABLE_PORTS: [10001, 10002, 10003, 10004, 10005, 10006]
CONNECTION_COUNTER: 0
reservePort: (callback) ->
if AVAILABLE_PORTS.length > 0
callback(AVAILABLE_PORTS.shift())
else
process.nextTick -> reservePort(callback)
releasePort: (port) -> AVAILABLE_PORTS.push(port) if AVAILABLE_PORTS.indexOf(port) == -1
server: net.createServer (client) ->
connectionId = CONNECTION_COUNTER++
log: (msg) -> sys.puts("[${new Date()}][${connectionId}] ${msg}")
log "OPEN: New Incoming Connection. ${AVAILABLE_PORTS.length} ports available."
client.pause()
client.setEncoding('binary')
reservePort (forwardedPort) ->
log "ROUTE: Found Available port. Routing to ${forwardedPort}"
destination: net.createConnection(forwardedPort, SERVER_ADDRESS)
client.addListener "connect", ->
destination.setEncoding('binary')
destination.addListener "connect", -> client.resume()
destination.addListener "data", (data) -> destination.pause() unless client.write(data, 'binary')
destination.addListener "drain", -> client.resume()
destination.addListener "end", ->
log "CLOSE: Connection closed by server releasing ${forwardedPort}"
destination.end()
releasePort(forwardedPort)
client.addListener "data", (data) -> client.pause() unless destination.write(data, 'binary')
client.addListener "drain", -> destination.resume()
client.addListener "end", ->
log "CLOSE: Connection closed by client releasing ${forwardedPort}"
client.end();
releasePort(forwardedPort)
server.listen(LISTEN_PORT)
description "node.js TCP Forwarding service"
author "Forward Internet Group"
start on startup
stop on shutdown
script
# We found $HOME is needed. Without it, we ran into problems
export HOME="/home/deploy"
/usr/local/bin/coffee /var/www/hive-port-forwarding/current/hive-port-forwarding.coffee 2>&1 >> /var/log/hive-port-forwarding.log
end script
respawn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment