Socket.IO-如何获取已连接套接字/客户端的列表? [英] Socket.IO - how do I get a list of connected sockets/clients?

查看:467
本文介绍了Socket.IO-如何获取已连接套接字/客户端的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取当前已连接的所有套接字/客户端的列表.

I'm trying to get a list of all the sockets/clients that are currently connected.

io.sockets不返回数组.

我知道我可以使用数组保留自己的列表,但是出于以下两个原因,这并不是最佳解决方案:

I know I could keep my own list using an array, but don't think this is an optimal solution for 2 reasons:

  1. 冗余. Socket.IO已经保留了此列表的副本.

  1. Redundancy. Socket.IO already keeps a copy of this list.

Socket.IO提供了为客户端设置任意字段值的方法(即:socket.set('nickname', 'superman')),因此,如果我要维护自己的列表,则需要跟上这些更改.

Socket.IO provides method to set arbitrary field values for clients (i.e: socket.set('nickname', 'superman')) so I'd need to keep up with these changes if I were to maintain my own list.

帮助?

推荐答案

在Socket.IO 0.7中,命名空间上有一个clients方法,该方法返回所有连接的套接字的数组.

In Socket.IO 0.7 you have a clients method on the namespaces, this returns a array of all connected sockets.

没有命名空间的API:

API for no namespace:

var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`

对于命名空间

var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`

希望这对以后的人有帮助

Hopes this helps someone in the future

注意::此解决方案适用于1.0之前的版本

NOTE: This Solution ONLY works with version prior to 1.0


更新2020年3月6日

从1.x及更高版本开始,请参阅此链接:

From 1.x and above, please refer to this link: getting how many people are in a chat room in socket.io

这篇关于Socket.IO-如何获取已连接套接字/客户端的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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