Flash Socket.io Message Multiple Times

I tried to find out node and started creating mashup with socket.io Message transport started, but I ran into some problems.

The message event is triggered several times, which leads to the appearance of one message that appears several times in the recipient field. I directed the socket to exports.chat and wondered if this caused a problem?

To narrow down the problem: messages run the number of times = client connection sequence. That is, if the client connects second, his messages will be triggered twice. three times for a third-party client.

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); } }); }); }; 
+6
source share
3 answers

All of the socket.io code should go beyond the external.chat function. Socket IO must communicate with the http / app server, you should not process it in every request.

messages run the number of times = client connection sequence

What actually happens is that every time a new request arrives, you register an event handler for the message, so it is launched as many times as you have accessed the chat URL.

 io.socket.on('message', function (data) {...}) 
+5
source

I believe that this incorrect behavior is due to the fact that you are trying to use one of several built-in / reserved event names of the "message" as an application-specific message. To confirm, change your event name to "message2" or something else and see if the problem goes away. I believe that at least “connect”, “disconnect” and “message” are reserved. https://github.com/LearnBoost/socket.io/wiki/Exposed-events

+1
source

I had the same problem. The solution is to close all of your listeners in the socket.on ('disconnect') event, this is what my code looks like -

  socket.on('disconnect', function () { socket.removeAllListeners('send message'); socket.removeAllListeners('disconnect'); io.removeAllListeners('connection'); }); 

It’s impossible to call it a shutdown, not sure, but I do not care.

+1
source

Source: https://habr.com/ru/post/955195/


All Articles