D
D
Denisca Gareev2020-07-25 19:54:57
Node.js
Denisca Gareev, 2020-07-25 19:54:57

How to listen on multiple ports and addresses in http.js?

How to listen on multiple ports and addresses in http.js?
Example for one port and address:

var fs = require("fs");
var rd = require("readline-sync");
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var config = JSON.parse(fs.readFileSync("./config.json"));
var port = 0;
switch(config.port){
  case "default":
    port = 3000;
  break;
  case "input":
    port = rd.question("Enter port, please: ");
  break;
  default:
    if(config.port / 1 != NaN){
      port = config.port;
    }else{
      throw new Error("Please check the port in config file.");
    }
  break;
}

app.use((req, res, next)=>{
  	res.write("Hello, world!");
  	res.end();
})

io.on('connection', function(socket){});

http.listen(port, config.address, function(){
  console.log("Server is started on address: "+config.address+" and port: "+port);
});


How about for multiple

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2020-07-25
@Denisca2828

You will have to raise 2 http server instances, each on its own port and address.
In principle, they can be used with a common app, since both req and res have a socket property, which is a net.Socket instance, which means you can get the address and port from it:
https://nodejs.org/dist/latest- v14.x/docs/api/http...
https://nodejs.org/dist/latest-v14.x/docs/api/http...
https://nodejs.org/dist/latest-v14. x/docs/api/net....

var app = require('express')();
var http = require('http');
var server1 = http.createServer(app);
var server2 = http.createServer(app);

server1.listen(PORT1, ADDRESS1);
server2.listen(PORT2, ADDRESS2);

io, it’s true that you will have to create 2 instances, but again, you can hang common event handlers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question