Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 630
onar Avatar asked Jan 07 '15 15:01

onar


People also ask

Does Socket.IO auto reconnect?

In the first case, the Socket will automatically try to reconnect, after a given delay.

How many connections Socket.IO can handle?

As we saw in the performance section of this article, a Socket.IO server can sustain 10,000 concurrent connections.

How many messages per second can Socket.IO handle?

Load benchmarks Here we can see that the HTTP benchmark peaks at about~950 requests per second while Socket.io serves about ~3900 requests per second.

Does Socket.IO guarantee order?

When using Socket.io with WebSockets, packet order is guaranteed to be maintained.


1 Answers

The solution is:

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

change to

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

For more information read the issue on github

like image 90
onar Avatar answered Oct 16 '22 01:10

onar