1

I am trying to make a server which listens on a internet facing port and forwards incoming http requests to an internal express server listening at another port. Following is the relevant part of the code I'm using.

var net = require('net');

var server = net.createServer();

server.listen(addr.from[3], addr.from[2], function(){
  console.log('Server listening');
});

server.on('connection',function(from){
   console.log('Client connected from '+ from.remoteAddress);
   var to = net.createConnection({
     host: addr.to[2],
     port: addr.to[3]
   });

   from.pipe(to);
   to.pipe(from);

   from.on('error',function(err){
     winston.error('Error at unix box'+err);
     to.end();
   });

   to.on('error',function(err){
      winston.error('Error at middleware server'+err);
      from.end();
   });

  from.on('end',function(){
      console.log('Client disconnected ');
      to.end();
  });

  to.on('end',function(){
      console.log('Middleware disconnected');
      from.end();
  });

});

The problem I'm encountering is that, when I open "ip:port" in the browser (which would be the internet facing port) I'm getting messages multiple "client connected from xxxxxx" msgs on the console. Can anyone help me understand why this is happening?

1 Answers1

2

Whenever browser connects to a website it usually makes two requests: normal and to retrieve favicon.

Funny thing, is that the favicon request is not even displayed in browser developer tools.

To verify, you need to extract the request made, print it to server, and then observe why you get multiple requests. For that, connection might be too early, try hooking request event instead:

server.on('request', funtion(req, res) { console.log(req.url); });
alandarev
  • 8,349
  • 2
  • 34
  • 43
  • Thanks for the quick response. I tried hooking request event as you said. However, there is nothing getting printed. Also, I wanted to know the best place to hook my other events as 'connection' event results in duplicate event handler for the same client. – Jobin James Oct 24 '14 at 11:21
  • It does not duplicate, there are indeed two connections.. It is just one is the `GET "/"` or whatever, and other is `GET "/favicon.ico"` – alandarev Oct 24 '14 at 11:32
  • Bro, I would love to upvote your answer, but since I'm very new to stackoverflow, I donot possess the minimum 15 votes to upvote... sad..I know! – Jobin James Oct 28 '14 at 13:44
  • I shall mark your reply as answer as you helped me understand why this is happening. However, my issue still remains unsolved as I am trying to make a proxy-server with error handling as described in http://stackoverflow.com/questions/26584845/how-to-detect-when-target-server-is-down-in-http-proxy. Thanks again. – Jobin James Oct 28 '14 at 13:54