場景:node
你有若干機器,卻只有一臺能被外網訪問,若是要讓外網訪問到你其它機器上的服務,就須要作反向代理,在上一篇文章中,咱們用nodejs輕鬆實現了http反向代理。若是是TCP服務,例如mysql數據庫,一樣用nodejs來作實現一個反向代理也是很容易的。mysql
第一種方式:sql
var net = require('net'); // parse "80" and "localhost:80" or even "42mEANINg-life.com:80" var addrRegex = /^(([a-zA-Z\-\.0-9]+):)?(\d+)$/; var addr = { from: addrRegex.exec(process.argv[2]), to: addrRegex.exec(process.argv[3]) }; if (!addr.from || !addr.to) { console.log('Usage: <from> <to>'); return; } net.createServer(function(from) { var to = net.createConnection({ host: addr.to[2], port: addr.to[3] }); from.pipe(to); to.pipe(from); }).listen(addr.from[3], addr.from[2]);
以上代碼存到文件forwarder.js,使用方式:數據庫
node forwarder.js 3306 192.168.1.11:3306
第一個參數是本機監聽的端口,第二個參數是要轉發到目標機器的ip和端口。怎麼樣,是否是很簡單呢。socket
第二種方式:ui
var net = require('net'); var LOCAL_PORT = 3306; var REMOTE_PORT = 3306; var REMOTE_ADDR = "192.168.1.11"; var server = net.createServer(function (socket) { socket.on('data', function (msg) { console.log(' ** START **'); console.log('<< From client to proxy ', msg.toString()); var serviceSocket = new net.Socket(); serviceSocket.connect(parseInt(REMOTE_PORT), REMOTE_ADDR, function () { console.log('>> From proxy to remote', msg.toString()); serviceSocket.write(msg); }); serviceSocket.on("data", function (data) { console.log('<< From remote to proxy', data.toString()); socket.write(data); console.log('>> From proxy to client', data.toString()); }); serviceSocket.on("end", function () { socket.end(); }); }); }); server.listen(LOCAL_PORT); console.log("TCP server accepting connection on port: " + LOCAL_PORT);
第一種方式使用了socoket的pipe,第二種至關於本身實現了pipe功能。.net