I'm looking to get all individuals socket objects out of io.sockets
and iterate over each of them.
Something like:
for (socket in io.sockets.something()) {
// do something with each socket
}
Either I'm doing this wrong or I must be missing something. Thoughts?
I'm looking to get all individuals socket objects out of io.sockets
and iterate over each of them.
Something like:
for (socket in io.sockets.something()) {
// do something with each socket
}
Either I'm doing this wrong or I must be missing something. Thoughts?
Share Improve this question edited Nov 4, 2011 at 18:26 josh3736 145k34 gold badges226 silver badges270 bronze badges asked Nov 4, 2011 at 17:22 David ChouinardDavid Chouinard 6,8368 gold badges46 silver badges64 bronze badges 2- So, what's the problem or the question? – thejh Commented Nov 4, 2011 at 17:26
- I'm just curious, what would be the use case for this? – alessioalex Commented Nov 4, 2011 at 17:43
3 Answers
Reset to default 15The official method is:
io.sockets.clients().forEach(function (socket) { .. });
Or filter by rooms:
io.sockets.clients('roomname') .. same as above ..
This is advised over the suggestion above as socket.io's internal data structure could always be subject to change and potentially breaking all your code with future updates. You much less at a risk when you use this official
method.
This may or may not be 'documented', but works:
for (var id in io.sockets.sockets) {
var s = io.sockets.sockets[id];
if (!s.disconnected) {
// ...
// for example, s.emit('event', { ... });
}
}
Use io.sockets.clients()
:
io.sockets.clients().forEach(function(s) {
// ...
// for example, s.emit('event', { ... });
});
You can use the excellent node-inspector to attach to your app and inspect the contents of s
.
Get all sockets with no room:
for (let s of io.of('/').sockets) {
let socket = s[1];
socket.emit(...);}