Socket.io message event firing multiple times

So I had the same problem. The solution is to close all your listeners on the socket.on('disconnect') event, this is what my code looks like -

 socket.on('disconnect', function () {
                socket.removeAllListeners('send message');
                socket.removeAllListeners('disconnect');
                io.removeAllListeners('connection');
            });

Might not need to call it on disconnect, not sure but I do it anyway.


I think this misbehavior is because you are attempting to use one of the handful of built-in/reserved event names "message" as an application-specific message. To confirm, change your event name to "message2" or something else and see if the problem goes away. I believe at least "connect", "disconnect", and "message" are reserved. https://github.com/LearnBoost/socket.io/wiki/Exposed-events


The whole part of socket.io code has to go outside external.chat function. Socket IO has to bind with the http/app server, you should not handle it within each request.

the messages are firing the number of times = the sequence of connection of the client

What essentially happening is, each time a new request arrives you are registering a event handler for message, hence it is fired as many times as the you have accessed chat URL.

io.socket.on('message', function (data) {...})