场景:
你有若干机器,却只有一台能被外网访问,如果要让外网访问到你其它机器上的服务,就需要做反向代理,在上一篇文章中,我们用nodejs轻松实现了http反向代理。如果是TCP服务,例如mysql数据库,同样用nodejs来做实现一个反向代理也是很容易的。
第一种方式:
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和端口。怎么样,是不是很简单呢。
第二种方式:
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功能。