Today we are going to build a simple TCP proxy server. The scenario is the following one. We have got one host (the client) that establishes a TCP connection to another one (the remote).
client —> remote
We want to set up a proxy server in the middle, so the client will establish the connection with the proxy and the proxy will forward it to the remote, keeping in mind the remote response also.
With node.js is really simple to perform those kind of network operations.
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);
Simple, isn’t it?
Source code in github
Reblogged this on drndark.
it’s been long time and now nodejs have new api. Can you update the code above and extend it to support https?
I mark it in my to do list, but it isn’t in the first places. Anyway pull requests are always welcome
How is this supposed to establish connection request from a website. There’s connection but data cannot be sent.
That’s not about http. It’s just a raw tcp proxy.
Hi,
I use your nodejs proxy script (https://github.com/gonzalo123/nodejs.tcp.proxy) to my gps tracker. I send data from gps first to proxy (there I save current position) and next to gps tracker service. And everything works correctly, but just for a moment. After 2 minutes connection is aborted.
“Error: read ECONNRESET
at exports._errnoException (util.js:907:11)
at TCP.onread (net.js:558:26)”
You have any idea what’s going on? I spent a lot of time to search answer on google/stackoverflow, but unsuccessfully.
Without proxy server was ok.
Kindest regards,
Marcin