I use socket.io with node.js, the problem is that the sockets can be reconnected themselves, and then all the data (identical) come to the client 2 or more times, depending on the number of reconnections without updating the page, the code is taken from the official docks, How to solve this problem?

/* client */ socket.on('connect', function () { console.log('start connect'); socket.on('message', function (data) { switch(data.event){ case 'start': connected(data); break; case 'error': alert(data.text); break; case 'online': online(data.type); break; case 'message': message(data.UsInfo, data.text); } }); }); /* server */ var io = require('socket.io').listen(8081); // Навешиваем обработчик на подключение нового клиента io.sockets.on('connection', function (socket) { console.log("New connection :)"); var ID = (socket.id).toString().substr(2); var time = (new Date).toLocaleTimeString(); socket.on('message', function (data) { var time = (new Date).toLocaleTimeString(); switch(data.event){ case 'start': start(socket, ID, data.steamid); break; case 'bet': bet(data, game, socket, ID); break; case 'message': message(data.text, ID); break; } }); io.sockets.emit('game', { event: 'game', number: winner, text: 'РОЗЫГРЫШ'}); 
  • Give more information, sample code that you use to implement the connection node.js & socket.io - Shnur
  • @Shnur, jsfiddle.net/vv4m9uhn - Vladislav Siroshtan
  • @ Vladislav Siroshtan, everything that relates to the question should be in the question itself . Links can only serve as a supplement . - Dmitriy Simushev
  • and in case of a connection error, you do not re-create the connection on the client? something like socket.on('disconnect',...) - NumminorihSF
  • @NumminorihSF, the fact is that a new connection is automatically created, but the old one is not killed, because of this, data for the client comes 2 or more times after the break, only page reload helps - Vladislav Siroshtan

1 answer 1

The problem is that you create a subscription to the messages for each connection event. And this event is created even during reconnection, i.e. You have 1 socket on which additional listeners of messages are hung at each reconnection.

Leave socket.on('connect',...) on the socket.once('connect',...) client socket.once('connect',...) . This will allow only one response to the creation of a connection.

Or, take socket.on('message',...) beyond the response to the connection, nothing terrible will happen.

Well, the funniest option is to check with pens that you created this subscription (for example, using a boolean variable) if the previous 2 options are not satisfied.

  • Thank you very much, your answer solved the problem. - Vladislav Siroshtan