[英]In NodeJS, how do I re-establish a socket connection with another server that may have gone down?
[英]How do I spawn independent children and re-establish communication in node.js?
首先是代码:
test.js:
var cluster = require("cluster");
if (cluster.isMaster) {
var app = cluster.fork();
app.on("message", function(code) {
console.log("Parent received: " + code);
app.send("this is from the test.js parent");
});
}
else {
process.send("");
process.on("message", function(code) {
console.log("Child received: " + code);
process.send("this is from the test.js child");
require("./testobj.js");
process.exit(0);
});
}
testobj.js:
process.send("this is from testobj.js");
process.on("message", function(code) {
console.log("testobj.js received: " + code);
});
process.send("this is the second message from testobj.js");
while (true) {}
运行节点test.js的结果
Parent received:
Child received: this is from the test.js parent
Parent received: this is from the test.js child
Parent received: this is from testobj.js
Parent received: this is the second message from testobj.js
到目前为止,您已经了解了我的工作,目标是生成独立于父代的子流程,但仍保留双向通信。 到目前为止,该测试代码保留了子对父之间的通信,但不保留子对父之间的通信。 是否有人对如何保留或重新建立父母与孩子之间的沟通有任何建议?
while(true){}
永久冻结了该孩子的事件循环,尽管process.exit(0)
杀死了派生的工作者,但使其不再那么永久。 据我所知,您不能退出进程并保持通信(因为该进程实际上不再运行)。
通过添加更多事件侦听器,您应该能够更轻松地查看正在发生的情况。 fork事件有一个不错的示例,尽管它在您的app
变量而不是引用的cluster
变量上。
app.on('fork', function(worker) {
console.log('Worker forked: ' + worker.id);
console.log(worker);
});
app.on('listening', function(worker, address) {
console.log('Worker listening: ' + worker.id);
console.log(address);
});
app.on('exit', function(worker, code, signal) {
console.log('Worker exited: ' + worker.id);
console.log('Code: ' + code + ' Signal: ' + signal);
});
根据worker.send文档/示例,似乎可以使用else if(cluster.isWorker)
代替每个示例中的else
:
if (cluster.isMaster) {
var worker = cluster.fork();
worker.send('hi there');
} else if (cluster.isWorker) {
process.on('message', function(msg) {
process.send(msg);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.