KField
KField

Reputation: 151

Node JS TCP Proxy: Reuse socket in callback function

I'm trying to implement a TCP proxy in Node JS. I only have some experience with Javascript so I met a lot of problems along the way. I've done a lot of searching for this one but had no luck.

The problem occurs when browser sends a CONNECT request for HTTPS. My proxy will parse the host name and port, and then create a new socket that connects to the server. If all these steps went well, I will start forwarding message.

Part of my code looks like this:

var net = require('net');

var server = net.createServer(function(clientSock) {

    clientSock.on('data', function(clientData) {

         var host = // get from data
         var port = // get from data

         if (data is a CONNECT request) {

              // Create a new socket to server
              var serverSock = new net.Socket();

              serverSock.connect(port, host, function() {
                  serverSock.write(clientData);

                  clientSock.write('HTTP/1.1 200 OK\r\n');
              }

              serverSock.on('data', function(serverData) {
                  clientSock.write(serverData);
              }
         }
    }        
}

Since the CONNECT request needs both client socket and server socket open until one side closes the connection, the code above doesn't have this behavior. Every time I receive some data from client, I will create a new socket to server and the old one is closed.

Is there a way to store the server socket as a global variable so that the data event handler can reuse it? Or is there any other way to solve this?

Thanks a lot!!!!

Upvotes: 0

Views: 1396

Answers (1)

jfriend00
jfriend00

Reputation: 707826

You can just move the variable up to a higher scope so it survives across multiple events and then you can test to see if its value is already there:

var net = require('net');

var server = net.createServer(function(clientSock) {

    var serverSock;
    clientSock.on('data', function(clientData) {

         var host = // get from data
         var port = // get from data

         if (data is a CONNECT request) {

              // Create a new socket to server
              if (!serverSock) {
                  serverSock = new net.Socket();

                  serverSock.connect(port, host, function() {
                      serverSock.write(clientData);

                      clientSock.write('HTTP/1.1 200 OK\r\n');
                  }

                  serverSock.on('data', function(serverData) {
                      clientSock.write(serverData);
                  }
              } else {
                  serverSock.write(clientData);
              }
         }
    }        
}

Upvotes: 1

Related Questions