Node.js – creates one more connection after reconnecting

I am trying a simple chat application here with and node.js. Every time I restart the node.js server, automatically reconnects and somehow creates one more connection to the server, i.e. the client now receives the same chat message twice. How do I fix this?

Best Solution

By default on disconnect reconnects the lost connection, which re runs the connect event. So everytime it reconnects you add one more event listener for recieving messages. So you get multiple number of messages equal to server restarts/connection loss.

Incoming Chat: 
Disconnected                         //recieved by 1st listener
Connected                            //added 2nd listener
Disconnected                         //recieved by 1st listener
Disconnected                         //recieved by 2nd listener
Connected                            //added 3rd listener

You should listen to the first connect using once instead of on, which runs eventhandler the first time only. Try

iosocket.once('connect', function () {

instead of

iosocket.on('connect', function () {