Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running node.js http server on multiple ports

Please can anybody help me to find out how to get the server socket context in node.js, so that i will come to know request came on which port number on my server. I can read the server port if i request using http headers but I want it through network and something like socket context which tells request came on which port number.

Here is the 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);
});
like image 842
Anuradha Singh Avatar asked Oct 10 '13 13:10

Anuradha Singh


People also ask

Can an HTTP server listen on multiple ports?

You can't listen on multiple ports for a single http. Server instance. listen on each port you want.

How many TCP connections can NodeJS handle?

There is no limitation to the number of connections which can be maintained on a single port (although, in practice, there may be operating system or hardware limitations).

How many concurrent HTTP requests can node js handle?

JS can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.


1 Answers

The req object has a reference to the underlying node socket. You can easily get this information as documented at: 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 show the local and remote socket address information.

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);
});
like image 70
Tim Caswell Avatar answered Oct 02 '22 12:10

Tim Caswell