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?
The 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(...);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With