简体   繁体   中英

How to create server instance in master in nodejs cluster? (both in worker and master)

The following code snippet is throwing error. Is there a way to achieve the following functionality ? If not why it is not possible to create server instance in nodejs cluster master?

var cluster = require('cluster');
var http = require('http');

if (cluster.isMaster) {

  var numCPUs = require('os').cpus().length;
  for (var i = 0; i < numCPUs; i++) {
       cluster.fork();
  }

  // How to create server instance in master?
  // It is throwing error when I create server like below.
  http.Server(function(req, res) {
     res.writeHead(200);
     res.end("hello worlddddd\n");
  }).listen(8000);
} else {
  http.Server(function(req, res) {
      res.writeHead(200);
      res.end("hello world\n");
  }).listen(8000);

}

The error that I got when running this code seems to point to the address:port combination already being in use. Change the port that your master server is listening on, and that should resolve the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM