Scene:
You have a number of machines, but only one can be accessed by the external network, if you want to let the outside network access to your other services on the machine, you need to do reverse proxy, in the previous article, we used Nodejs easy to implement the HTTP reverse proxy. If it is a TCP service, such as a MySQL database, it is also easy to use Nodejs to implement a reverse proxy.
The first way:
Var net = require (' net ');// parse " 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]);
The above code is stored in the file Forwarder.js, using the method:
Node Forwarder.js 3306 192.168.1.11:3306
The first parameter is the port that the native listens to, and the second parameter is the IP and port to forward to the target machine. How about, isn't it very simple.
The second way:
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 ()); &nbSp; 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 ()); }); }); Server.listen (Local_port); Console.log ("tcp server accepting connection on port: " + local_port);
The first way to use the Socoket pipe, the second equivalent to achieve the pipe function.