Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io—restrict number of maximum connections per namespace

I have a little webapp built on node.js, express and socket.io. Within that, I am using two namespaces creates like that:

lists = io.of('/lists'),
views = io.of('/view'),

What I would like to do, is to restrict the number of connections in the /views namespace. Is there any way to make that with socket.io? I have had a look at the docs, but there wasn't anything to find there.

Any Ideas how to do that?

Thanks in ahead!

like image 253
philipp Avatar asked Aug 24 '15 19:08

philipp


1 Answers

You can make a simple counter (if necessary - to extend the class):

var lists = io.of('/lists');
lists.max_connections = 10;
lists.current_connections = 0;

lists.on('connection', function(socket){
  if (this.current_connections >= this.max_connections) {
    socket.emit('disconnect', 'I\'m sorry, too many connections');
    socket.disconnect();
  } else {
    this.current_connections++;
    socket.on('disconnect', function () {
      this.current_connections--;   
    });
    /** something useful **/ 
  }
});

Upd: If you want the client to continue to attempt to connect to the server, use:

socket.conn.close();

Instead:

socket.disconnect();
like image 172
stdob-- Avatar answered Sep 28 '22 07:09

stdob--