Socket.io 1.2.1 How to fix double events after reconnecting

The socket.io block says that in version 1.2.1

"README corrects to prevent double events in the example when reconnecting [@nkzawa]"

I downloaded version 1.2.1 for the client and server, but after reconnecting it still raises events twice. Or should I do something with the readme file?

I tried this method to reconnect and it worked, but I can use it for production. Is it correct?

socket.disconnect() // remove socket object socket = undefined // connect again socket = io.connect({'forceNew':true}) 

Like I said, is this the right way or does it have disadvantages?

UPDATE, added code

server code

 socket.on('client_emited', function(data){ socketIO.to('this socket id').emit('server_emitted'); }) 

client code

 var socket; function connectSocket () { if (!socket) socket = io({'forceNew':true}); else socket.connect(); } socket.on('connect', function(){ console.log('CONNECTED TO SOCKET.IO SERVER. SENDING "client_emited" EVENT'); socket.emit('client_emited'); }); socket.on('server_emited', function(){ console.log('RECEIVED "server_emited" EVENT'); }); socket.connect(); // here console shows 'CONNECTED TO SOCK...' and 'RECEIVED "server_e...' 1 time socket.disconnect(); socket.connect(); // here console shows 'CONNECTED TO SOCK...' 2 times and 'RECEIVED "server_e...' 4 times time 

and the server receives the client_emit event two times

+5
source share
1 answer

Decision:

 socket.on('connect', function(){....}); 

change to

 socket.once('connect', function(){....}); 

Read the github question for more info

+6
source

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


All Articles