socket.io—限制每个命名空间的最大连接数

socket.io—restrict number of maximum connections per namespace

我有一个基于 node.js、express 和 socket.io 的小网络应用程序。在其中,我使用了两个这样创建的命名空间:

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

我想做的是限制 /views 命名空间中的连接数。有什么办法可以用 socket.io 做到这一点吗?我已经查看了文档,但在那里找不到任何东西。

任何想法如何做到这一点?

提前致谢!

您可以制作一个简单的计数器(如果需要 - 扩展 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: 如果你想让客户端继续尝试连接服务器,使用:

socket.conn.close();

改为:

socket.disconnect();