onar
onar

Reputation: 497

socket.io 1.2.1 How to fix double events after reconnect

In socket.io's blog says, that in version 1.2.1

"README fixes to prevent double events in the example upon reconnection [@nkzawa]"

I downloaded 1.2.1 version for client & server, But after reconnect it still call events two times. Or I should do something with readme file?

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

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

As I said is it right way or does it have cons?

UPDATE, added code

server side code

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

client side 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 "client_emit" event two times

Upvotes: 8

Views: 5754

Answers (1)

onar
onar

Reputation: 497

The solution is:

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

change to

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

For more information read the issue on github

Upvotes: 10

Related Questions