Running node.js http server on multiple ports

Please someone help me find out how to get the server socket context in node.js so that I know that the request came to which port number on my server. I can read the server port if I request the use of http headers, but I want it through the network and something like a socket context that reports a request about which port number.

Here is a sample code:

var http=require('http'); var url = require('url'); var ports = [7006, 7007, 7008, 7009]; var servers = []; var s; function reqHandler(req, res) { var serPort=req.headers.host.split(":"); console.log("PORT:"+serPort[1]);//here i get it using http header. } ports.forEach(function(port) { s = http.createServer(reqHandler); s.listen(port); servers.push(s); }); 
+7
javascript sockets
source share
1 answer

The req object has a reference to the base node socket. You can easily get this information as described on the page: http://nodejs.org/api/http.html#http_message_socket and http://nodejs.org/api/net.html#net_socket_remoteaddress

Here is your sample code modified to display information about local and remote sockets.

 var http=require('http'); var ports = [7006, 7007, 7008, 7009]; var servers = []; var s; function reqHandler(req, res) { console.log({ remoteAddress: req.socket.remoteAddress, remotePort: req.socket.remotePort, localAddress: req.socket.localAddress, localPort: req.socket.localPort, }); } ports.forEach(function(port) { s = http.createServer(reqHandler); s.listen(port); servers.push(s); }); 
+5
source

All Articles