请教关于socket.io与child_process产生的进程通信消息重复问题
发布于 10 年前 作者 vip1232 4677 次预览 最后一次回复是 10 年前 来自 问答
father.js 作为主进程里面使用child process模块,并且fork了child.js作为子进程
var cp = childProcess.fork(’./child.js’);
io.sockets.on(‘connection’, function (socket) {
socket.on(‘news’, function (data) { //接受客户端的消息,并向子进程cp发送消息
cp.send({msg:“to chilid”})
});
cp.on(‘message’,function(data){ //接受子进程cp返回的消息
console.log(“father listen:”+data.msg);
})
}
child.js process.on(‘message’, function(msg) { process.send({msg:“hello father”}) //收到father.js的消息后发回消息 })
然后问题来了,网页请求连接后: 第1次 打印 father listern:hello father 正常 第2次刷新网页 就会打印2条 father listern:hello father father listern:hello father 第3次 打印3条,后面每刷新一次打印条数就增加一条。
请问这是原因,该如何解决呢?
4 回复
你每次刷新页面就会建立一次
socket.io的链接 就会触发一次connection事件 你的cp就会增加一个对message的监听注册函数把你的监听函数放外面就好了
cp.on('message’,function(data){ //接受子进程cp返回的消息console.log("father listen:"+data.msg);})@showen 非常感谢!
那么放到外面后,我想实现的是给连接socket的用户发送cp传来的消息,那么就还需要存一下连接用户的socke id吧?
@vip1232 是的 需要维护用户和各自的socket链接
@showen 感谢!