Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does socket.io reconnects re-run connect?

I've built a simple web application that does some communication through a node.js server using socket.io.

When a user connects, node communicates back info which tells the client to subscribe to certain events. That works fine.

But if you let the browser set idle, the client ends up subscribed to the events twice. The subscription process works like this:

When a user connects node.js gets a 'adduser' message

The two key things that hapen in that function are this:

socket.on('adduser', function(data)
   <snip>
   socket.emit('nodeinfo', {node_id: NODE_ID});
   socket.emit('update', {msg: 'you are connected'});

The socket.emit('nodeinfo') signals the client to subscribe to the events.

So the client has

socket.on('nodeinfo', function(data) { ... }

The thing is it never say 'you are connected' twice, none of the console.log() functions in 'adduser' get called again on the node side. The only thing that appears to happen is node.js emits nodeinfo again (or so the client thinks) causing the client to re-subscribe.

Can anyone explain to me how re-connects in socket.io work and how this may happen?

like image 362
frank stallone Avatar asked Mar 12 '12 14:03

frank stallone


People also ask

Does Socket.IO auto reconnect?

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

Does Socket.IO reconnect after disconnect?

Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.

How do I reconnect a socket IO client?

socket = io. connect( 'http://127.0.0.1:3000', { reconnection: true, reconnectionDelay: 1000, reconnectionDelayMax : 5000, reconnectionAttempts: 99999 } ); socket. on( 'connect', function () { console. log( 'connected to server' ); } ); socket.

How can I tell if Socket.IO is connected?

You can check the socket. connected property: var socket = io. connect(); console.


1 Answers

By default the client tries to reconnect after a disconnect. This can be changed if you like: socket.io client

If reconnected, the server will see a new connection and it is up to you to implement logic to identify the new connection with the previous one. So in practice - instead of implementing your adduser logic upon "connection" do it (or not) after the client sends some info to the server.

like image 190
Mark Avatar answered Sep 28 '22 00:09

Mark