node.js socket.io 房间总用户数 [英] node.js socket.io room total of users

查看:48
本文介绍了node.js socket.io 房间总用户数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算特定房间中的用户总数,并将其广播给该房间中的所有人.

I'm trying to count the total number of users in a specific room and broadcast it to all the people in that room.

这是我所拥有的,但出现错误:

Here is what I have but I get an error:

var clients = io.sockets.clients(cc.lowerCase(data.roomname)).length;
         io.sockets.in(cc.lowerCase(data.roomname)).emit('updatetotal', { total: clients });

错误:

TypeError: Object #<Namespace> has no method 'clients'

谢谢.

推荐答案

自 socket.io 1.0 以来,其 API 发生了重大变化,因此旧代码可能无法正常工作.

Since socket.io 1.0 its API was significantly changed so the old code might not work.

要获取房间中的客户数量,您可以使用此功能:

To get the number of clients in a room you can use this function:

var getUsersInRoomNumber = function(roomName, namespace) {
    if (!namespace) namespace = '/';
    var room = io.nsps[namespace].adapter.rooms[roomName];
    if (!room) return null;
    var num = 0;
    for (var i in room) num++;
    return num;
}

或更简洁:

var getUsersInRoomNumber = function(roomName, namespace) {
    if (!namespace) namespace = '/';
    var room = io.nsps[namespace].adapter.rooms[roomName];
    if (!room) return null;
    return Object.keys(room).length;
}

这个函数需要两个参数:

This function takes two agruments:

  • 房间名称
  • namespace (可选) default = '/'
  • roomName
  • namespace (optional) default = '/'

发送消息给这个房间的用户只使用.to方法:

To send message to users of this room only use .to method:

io.to(yourRoomName).emit('updatetotal', { total: getUsersInRoomNumber(yourRoomName) });

这篇关于node.js socket.io 房间总用户数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆