简体   繁体   English

socket.io-restrict每个命名空间的最大连接数

[英]socket.io—restrict number of maximum connections per namespace

I have a little webapp built on node.js, express and socket.io. 我在node.js,express和socket.io上构建了一个小的webapp。 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. 我想做的是限制/views命名空间中的连接数。 Is there any way to make that with socket.io? 用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! 提前谢谢!

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM