我使用的是较新版本的socket.io,但我无法弄清楚如何获取套接字对象的列表。我已经关注了一些教程和StackOverflow的答案,例如:
How to get all the sockets connected to Socket.io
我也查看了文档,但它没有多大帮助。我发现的所有帖子都解释了如何获取socketIds,但我需要自己的套接字,所以我只能向某些套接字发射。
那么你如何自己获得实际的套接字,或者在较新版本的Socket中这是不可能的呢?
答案 0 :(得分:2)
您可以选择几个:
// An object with socket.id as property and socket object as value
// You could iterate this with for/in or use `Object.keys()` to get the ids
// and then access each socket by id
// io.sockets.connected
var ids = Object.keys(io.sockets.connected);
ids.forEach(function(id) {
var socket = io.sockets.connected[id];
// do something with socket here
});
// an array of sockets which you can iterate directly as an array.
// io.sockets.sockets
io.sockets.sockets.forEach(function(socket) {
// do something with socket here
});
您还可以单独访问命名空间:
// array of sockets in this namespace
io.nsps['/'].sockets
// map of socket ids in this namespace
io.nsps['/'].connected