Socket.io消息事件多次触发 [英] Socket.io message event firing multiple times
问题描述
我试图学习节点,并开始使用socket.io创建混搭消息传输已经开始,但是我遇到了一些麻烦.
I was trying to learn node and started creating a mashup with socket.io The message transportation have begin but I have run into some trouble.
消息事件触发多次,导致一条消息多次出现在收件人的信箱上.我已经将套接字路由到 exports.chat
,并且想知道这是否是导致问题的原因?
The message event is firing multiple times leading to a single message appearing multiple times on the recipient's box. I have routed the socket to exports.chat
and was wondering if that is causing the problem?
要缩小问题的范围,请执行以下操作:消息触发的次数=客户端连接的顺序.也就是说,如果客户端第二次连接,则他的消息将触发两次.客户端连接第三次的三倍.
To narrow down the problem: the messages are firing the number of times = the sequence of connection of the client. That is, if a client connects second, his messages will fire twice. three times for the client connecting third.
这是代码段:
Here is the code snippet:
exports.chat = function(io, pseudoArray, req, res){
res.render('chat', {title: 'ChatPanel.'});
var users = 0;
io.sockets.on('connection', function (socket) { // First connection
users += 1;
// reloadUsers(io, users);
socket.on('message', function (data) { // Broadcast the message to all
if(pseudoSet(socket)) {
var transmit = {date : new Date().toISOString(), pseudo : returnPseudo(socket), message : data};
socket.broadcast.emit('message', transmit);
console.log("user "+ transmit['pseudo'] +" said \""+data+"\"");
}
});
socket.set('pseudo', req.session.user, function(){
pseudoArray.push(req.session.user);
socket.emit('pseudoStatus', 'ok');
console.log("user " + req.session.user + " connected");
});
socket.on('disconnect', function () { // Disconnection of the client
users -= 1;
// reloadUsers();
if (pseudoSet(socket)) {
var pseudo;
socket.get('pseudo', function(err, name) {
pseudo = name;
});
var index = pseudoArray.indexOf(pseudo);
pseudo.slice(index - 1, 1);
}
});
});
};
推荐答案
socket.io代码的整个部分都必须位于external.chat函数之外.套接字IO必须与http/app服务器绑定,您不应在每个请求中处理它.
The whole part of socket.io code has to go outside external.chat function. Socket IO has to bind with the http/app server, you should not handle it within each request.
消息触发次数=客户端连接顺序
the messages are firing the number of times = the sequence of connection of the client
本质上是,每次新请求到达时,您都在注册事件消息处理程序,因此,它被触发的次数与您访问聊天URL的次数相同.
What essentially happening is, each time a new request arrives you are registering a event handler for message, hence it is fired as many times as the you have accessed chat URL.
io.socket.on('message', function (data) {...})
这篇关于Socket.io消息事件多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!