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