Created
September 19, 2016 09:01
-
-
Save leizongmin/93f9a3bfb780e1038a381e9bf9e4c74d to your computer and use it in GitHub Desktop.
tcp proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const net = require('net'); | |
function printUsage() { | |
console.log('Usage:'); | |
console.log(' $ node tcp-proxy 3306 remote.ucdok.com 3306'); | |
process.exit(); | |
} | |
const port = parseInt(process.argv[2], 10); | |
if (isNaN(port)) { | |
printUsage(); | |
} | |
const remoteAddr = String(process.argv[3]).trim(); | |
if (!remoteAddr || remoteAddr === 'undefined') { | |
printUsage(); | |
} | |
const remotePort = parseInt(process.argv[4], 10); | |
if (isNaN(remotePort)) { | |
printUsage(); | |
} | |
function log() { | |
process.stdout.write((new Date()).toTimeString() + ' '); | |
console.log.apply(console, arguments); | |
} | |
function addrInfo(conn) { | |
return [ conn.remoteAddress, conn.remotePort ].join(':'); | |
} | |
const server = net.createServer(conn => { | |
log('new client connection:', addrInfo(conn)); | |
const remote = net.connect(remotePort, remoteAddr, () => { | |
log('connected to remote server'); | |
}); | |
pipe(conn, remote); | |
pipe(remote, conn); | |
remote.on('close', () => { | |
log('remote closed: ', addrInfo(remote)); | |
closeAll(); | |
}); | |
remote.on('error', err => { | |
log('remote error: ', addrInfo(remote), err); | |
}); | |
conn.on('close', () => { | |
log('client closed: ', addrInfo(conn)); | |
closeAll(); | |
}); | |
conn.on('error', err => { | |
log('client error: ',addrInfo(conn), err); | |
closeAll(); | |
}); | |
function closeAll() { | |
log('close all: ', addrInfo(conn)); | |
remote.destroy(); | |
conn.destroy(); | |
} | |
function pipe(a, b) { | |
a.on('data', d => b.write(d)); | |
a.on('end', () => b.end()); | |
} | |
}); | |
server.listen(port, err => { | |
console.log('server started: %s => %s:%s', port, remoteAddr, remotePort); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment