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?
In the first case, the Socket will automatically try to reconnect, after a given delay.
Socket disconnects automatically, reconnects, and disconnects again and form a loop. #918.
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.
You can check the socket. connected property: var socket = io. connect(); console.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With