本人菜鸟一个,刚开始学习nodejs,看官方关于cluster模块的message方法时,碰到如下代码码: var cluster = require(‘cluster’); var http = require(‘http’);
if (cluster.isMaster) {
// Keep track of http requests var numReqs = 0; setInterval(function() { console.log(“numReqs =”, numReqs); }, 1000);
// Count requestes function messageHandler(msg) { if (msg.cmd && msg.cmd == ‘notifyRequest’) { numReqs += 1; } }
// Start workers and listen for messages containing notifyRequest var numCPUs = require(‘os’).cpus().length; for (var i = 0; i < numCPUs; i++) { cluster.fork(); }
Object.keys(cluster.workers).forEach(function(id) { cluster.workers[id].on(‘message’, messageHandler); });
} else {
// Worker processes have a http server. http.Server(function(req, res) { res.writeHead(200); res.end(“hello world\n”);
// notify master about the request
process.send({ cmd: 'notifyRequest' });
}).listen(8000); }
其中的process.send() 让我有点纳闷,因为我看了文档中process是没有send方法的,而且我单独写也是报错说send()方法未定义,但是上面的例子确认正确运行。 请大侠们指点小弟一二,谢谢!!
大概是在子进程中才有process.send()的吧
我自己捣鼓了半天,貌似是你说的那样! var cluster = require(“cluster”); if(cluster.isMaster){ var worker = cluster.fork() worker.on(“message”, function(msg){ console.log(msg); }); }else{ process.send({as: ‘asasdf’}); } 只要这样写就可以。。。把process.send()放外面就报错
多谢了!
worker.send(message, [sendHandle]): master给worker发送消息。 注:worker给发master发送消息要用process.send(message)
worker 与worker之间有api可以通信吗?