用node实现服务器端口转发

var net = require('net');

proxyPort("8787","139.10.20.3","8080");//源端口,目标服务器,目标端口

function proxyPort(srcport,destServer,destport)
{
  var server = net.createServer(function(c) { //'connection' listener

    c.on('end', function() {
        console.log('src disconnected');
    });

    var client = net.connect({port: destport,host:destServer},function() { //'connect' listener
         //console.log('ok....');
         c.on('data', function(data) {
             //console.log(data.length);
           client.write(data);
         });
    });

    client.on('error', function(err) {
     console.log("dest=" + err);
     c.destroy();
    });

    c.on('error', function(err) {
     console.log("src" + err);
     client.destroy();
    });

    client.on('data', function(data) {
     c.write(data);
    });

    client.on('end', function() {
     console.log('dest disconnected ');
    });

  });
  server.listen(srcport, function() { //'listening' listener
   console.log('server bound' + srcport);
  });
}

把上面代码保存为一个文件,如portForwarding.js 那么运行命令是:

nohup node portForwarding.js > ~/portForwarding.log 2>&1 &

如果要关闭,请执行ps -ef | grep portForwarding,然后kill -9 相关进程

用node实现服务器端口转发