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

Socket.io connection piles up on each refresh

Socket.io connection piles up on each refresh

Problem

I'm using socket.io with node.js and inside one of my routes, I have the connection event handler.

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

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

Each time I Refresh the page that's calling this route, it seems to keep adding up, for example, if I refresh 5 times, I'll end up having 5 'connect' messages, on a single refresh, in the log.

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

Thanks!

Edit:

When I refresh repeatedly, I get this error:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit

I can increase the limit, but I have a feeling that's no the correct solution.

Problem courtesy of: dzm

Solution

You have to place your code outside of your request handler (that gets called on each request). This code is supposed to handle incoming connections for all clients (not for each request). In your example it creates a new event listener on every request, you only want one !

Solution courtesy of: stewe

Discussion

View additional discussion.



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

Share the post

Socket.io connection piles up on each refresh

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×