Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  192] [ 6]  / answers: 1 / hits: 23704  / 11 Years ago, thu, october 3, 2013, 12:00:00

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.



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);
}
});
});
};

More From » node.js

 Answers
6

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




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) {...})

[#75252] Wednesday, October 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rossthomasn

Total Points: 122
Total Questions: 78
Total Answers: 105

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;