Building a simple TCP proxy server with node.js

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 = "";

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.on("data", function (data) {
            console.log('<< From remote to proxy', data.toString());
            console.log('>> From proxy to client', data.toString());

console.log("TCP server accepting connection on port: " + LOCAL_PORT);

Simple, isn’t it?
Source code in github

About Gonzalo Ayuso

Web Architect. PHP, Python, Node, Angular, ionic, PostgreSQL, Linux, ... Always learning.

Posted on September 17, 2012, in node.js, Technology and tagged , , , . Bookmark the permalink. 7 Comments.

  1. Reblogged this on drndark.

  2. it’s been long time and now nodejs have new api. Can you update the code above and extend it to support https?

  3. How is this supposed to establish connection request from a website. There’s connection but data cannot be sent.

  4. Hi,
    I use your nodejs proxy script ( 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,

  1. Pingback: Building a simple TCP proxy server with node.js | - Developers Network

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: