Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Does reconnects re-run connect?

Does reconnects re-run connect?


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

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)
   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 work and how this may happen?

Problem courtesy of: frank stallone


By default the client tries to reconnect after a disconnect. This can be changed if you like: 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.

Solution courtesy of: Mark


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Does reconnects re-run connect?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription