http server run 2 ports code example

Example 1: how to run multple port node

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);
});

Example 2: how to run multple port node

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);
});

Tags:

Misc Example