利用Node.js构建一个简单的TCP代理服务器
jopen
12年前
今天我们将给大家介绍如何利用Node.js构建一个简单的TCP代理服务器(TCP proxy server)。该方案:我们已经有了一台主机(客户端)建立一个TCP连接到另外一台(远程机)
client —> remote
我们要在中间架设一个代理服务器,客户端与代理建立连接,然后代理转发到远程,并保持远程响应。
利用node.js来实现这种类型的网络操作将会非常简单,详见如下代码:
client —> proxy -> remote
var net = require('net'); var LOCAL_PORT = 6512; var REMOTE_PORT = 6512; var REMOTE_ADDR = "192.168.1.25"; 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()); }); }); }); server.listen(LOCAL_PORT); console.log("TCP server accepting connection on port: " + LOCAL_PORT);是不是很简单呢?
源程序下载 github
Open经验库编译自:http://css.dzone.com/articles/building-simple-tcp-proxy