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

查看:34
本文介绍了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 及以上,请参考此链接:在 socket.io 中获取聊天室中有多少人

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天全站免登陆