0

I have this example script from node describing how to send messages from either a Master or worker process using cluster. When I run this script, I am unable to verify the message from either the Master or worker. It appears the worker.on statement is not executing.

Can anyone explain how I can verify these messages from either process on the console during runtime and why the worker.on statement is not working? I would like to create a two-way communication handshake.

if (cluster.isMaster) {
  var worker = cluster.fork();
  worker.on("message", function(code) {
       console.log("Parent received: " + code);
       worker.send("this is from the test.js parent");
   });
} else if (cluster.isWorker) {
  process.on('message', function(msg) {
    process.send(msg);
  });
}

Other SO discussion(link1, link2)

Community
  • 1
  • 1
Val
  • 1,260
  • 5
  • 23
  • 39

1 Answers1

4

The tested and working answer to the question is as follows:

if (cluster.isMaster) {
  var worker = cluster.fork();

  // Receive messages from the worker and handles them in the master process.
  worker.on("message", function(code) {
            console.log("Parent "+worker.id+" received: " + code.msgFromWorker);
            worker.send({msgFromMaster:"this is parent responding to worker " + worker.id +" as standby"});
  });
} else if (cluster.isWorker) {

    // Send message to master process.
    process.send({msgFromWorker: 'This is from worker ' + process.pid + ' ready to respond.'});
    // Receive messages from the master process.
    process.on('message', function(msg) {
        console.log('Worker ' + process.pid + ' received: ', msg.msgFromMaster);
    });
}

Here is a link with further illustration to this answer type link

Val
  • 1,260
  • 5
  • 23
  • 39