7

用node实现服务器端口转发

 3 years ago
source link: https://blog.star7th.com/2019/06/2356.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

用node实现服务器端口转发

我们很多场景需要端口转发,如内网穿透,服务器之间的IP隐藏,网络加速,甚至“科学用网”等等。
下面尝试用node写一个小脚本,实现端口转发。其中proxyPort()函数可以执行多次,如果要实现多端口转发的话则把它复制几遍即可。

//端口转发
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 相关进程


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK