Steverino
Steverino

Reputation: 2266

How to get a list of connected socket objects (not socket IDs) in socket.io v1+?

I'm using a newer version of socket.io and I can't figure out how to get a list of socket objects. I've followed some tutorials and StackOverflow answers such as this one:

How to get all the sockets connected to Socket.io

I've also looked at documentation but it hasn't helped much. All posts I've found explain how to get socketIds, but I need the sockets themselves so I can emit just to certain sockets.

So how do you get the actual sockets themselves, or is this no longer possible in newer versions of Socket?

Upvotes: 1

Views: 897

Answers (1)

jfriend00
jfriend00

Reputation: 708046

You can have a couple choices:

// 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

});

You can also access namespaces separately:

// array of sockets in this namespace
io.nsps['/'].sockets

//  map of socket ids in this namespace
io.nsps['/'].connected

Upvotes: 2

Related Questions