Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

cluster.fork() - Start the server in a callback function #2044

Closed
subnetmarco opened this issue Nov 8, 2011 · 1 comment
Closed

cluster.fork() - Start the server in a callback function #2044

subnetmarco opened this issue Nov 8, 2011 · 1 comment
Labels

Comments

@subnetmarco
Copy link

I wrote the following piece of code, where I start an HTTP server in a child process only when a message is received by the master. The server is unreachable.

if (cluster.isMaster) {
    var child = cluster.fork();
    child.send({type:1, options:{port:8080, key:"12345"}});
} else {
    process.on("message", function (message) {
        if (message.type == 1) {
            http.Server(function(req, res) {
                doSomething(message.options.key);
            }).listen(message.options.port);
        }
    });
}
@bnoordhuis
Copy link
Member

Works for me. Your example, adapted:

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

if (cluster.isMaster) {
  var child = cluster.fork();
  child.send({type:1, options:{port:8080, key:"12345"}});
} else {
  process.on("message", function (message) {
    if (message.type == 1) {
      http.Server(function(req, res) {
        res.writeHead(200, {'Content-Length':'3'});
        res.end("OK\n");
      }).listen(message.options.port);
    }
  });
}
$ curl -s http://127.0.0.1:8080/
OK
$

You probably need to make sure that your server is binding to the right address.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants