Socket.io connection piling up on every update

I am using socket.io with node.js and inside one of my routes, I have a connection event handler.

            app.io.on('connection', function(socket) {
                    console.log('connect');

                    socket.on('disconnect', function(){
                        console.log('disconnect');
                        res.end();
                    });
            });

      

Every time I refresh the page that calls this route it seems like it keeps adding up, for example if I refresh 5 times I end up with 5 "connect" messages in one log update.

Is there a good way to limit this so that it doesn't?

Thank!

Edit:

On re-updating I get this error:

(node) warning: Possible EventEmitter memory leak detection. 11 listeners added. Use emitter.setMaxListeners () to increase the limit

I can increase the limit, but I have a feeling that there is no right solution.

+3


source to share


1 answer


You have to put your code outside of the request handler (which is called on every request). This code should handle incoming connections for all clients (not for every request). In your example, it creates a new event listener on every request, you only need one!



+4


source







All Articles