Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I do with a CONNECT event?

If I create a simple server in Node.JS

var httpServer = http.createServer(callback);

httpServer.on('connect', function(req, socket, head){
    console.log('connect');
});

httpServer.listen(3128, '192.168.0.2');

What should I do when I receive the connect event?

Background

  • This will be a proxy server, serving HTTP and HTTPS
  • Clients connect on port 3128
  • When a client makes an HTTPS request the connect event is fired

Ideally what I would like to do is, proxy the request to the end server, and then give the client the response.

But I can't see any API for doing that here. The connect callback doesn't have the usual arguments of (request, response), instead it accepts (request, socket, head).

How do I fulfil the request and issue a response?

like image 961
Drahcir Avatar asked Sep 18 '25 12:09

Drahcir


1 Answers

Answer rewritten from scratch

Here is simple example.
connect event handler have passed socket object which we have to tie with remote connection's socket.

httpServer.on('connect', function(req, socket, head) {
  var addr = req.url.split(':');
  //creating TCP connection to remote server
  var conn = net.connect(addr[1] || 443, addr[0], function() {
    // tell the client that the connection is established
    socket.write('HTTP/' + req.httpVersion + ' 200 OK\r\n\r\n', 'UTF-8', function() {
      // creating pipes in both ends
      conn.pipe(socket);
      socket.pipe(conn);
    });
  });

  conn.on('error', function(e) {
    console.log("Server connection error: " + e);
    socket.end();
  });
});
like image 124
ataman Avatar answered Sep 20 '25 05:09

ataman