Node.js |工作进程:如何验证主进程和工作进程之间的双向通信

时间:2014-07-09 05:00:23

标签: javascript node.js heroku cluster-computing console.log

我有来自node的示例脚本,描述了如何使用群集从主进程或工作进程发送消息。当我运行此脚本时,我无法验证来自Master或worker的消息。似乎worker.on语句没有执行。

任何人都可以解释我如何在运行时从控制台上的任一进程验证这些消息以及为什么worker.on语句不起作用?我想创建一个双向通信握手。

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

其他SO讨论(link1link2

1 个答案:

答案 0 :(得分:4)

对问题的测试和工作答案如下:

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

以下是此答案类型link

的进一步说明链接