CNode

请教关于socket.io与child_process产生的进程通信消息重复问题

问答
Vvip1232发布于11 年前最后回复11 年前4 回复4829 浏览0 收藏

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)

S
showen#1·11 年前

你每次刷新页面就会建立一次socket.io的链接 就会触发一次connection事件 你的cp就会增加一个对message的监听注册函数

把你的监听函数放外面就好了 cp.on('message’,function(data){ //接受子进程cp返回的消息 console.log("father listen:"+data.msg); })

V
vip1232#2·11 年前
引用 showen你每次刷新页面就会建立一次socket.io的链接 就会触发一次connection事件 你的cp就会增加一个对message的监听注册函数 把你的监听函数放外面就好了 cp.on('mess...

@showen 非常感谢!

那么放到外面后,我想实现的是给连接socket的用户发送cp传来的消息,那么就还需要存一下连接用户的socke id吧?

参与回复
登录后即可参与回复。登录