title: Node JS TCP Proxy: Reuse socket in callback function
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Part of my code looks like this:</p>
  
  <pre><code>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);
                }
           }
      }        
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>Thanks a lot!!!!</p>