Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving all socket objects in io.socket

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?

like image 764
David Chouinard Avatar asked Nov 04 '11 17:11

David Chouinard


3 Answers

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.

like image 163
3rdEden Avatar answered Oct 23 '22 06:10

3rdEden


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.

like image 27
josh3736 Avatar answered Oct 23 '22 08:10

josh3736


Get all sockets with no room:

for (let s of io.of('/').sockets) {
let socket = s[1];
socket.emit(...);}
like image 40
Eyni Kave Avatar answered Oct 23 '22 08:10

Eyni Kave