teamyates
teamyates

Reputation: 434

How to find all sockets in room using the latest version of Socket.io

So, using socket.io version < 1.0 you could use:

var clients = io.sockets.clients('room');

To get all sockets in the room 'room'.

However now with the lastest version of socket.io this is not possible, I haven't found a solution yet that works for the latest version and I do not wish to downgrade versions to run my application.

Upvotes: 3

Views: 5087

Answers (3)

TmTron
TmTron

Reputation: 19441

according to the socket.io 2.0 docs

io.in('room').clients((error, clients) => {
  if (error) throw error;
  console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
});

and to get the socket for the client-id:

io.sockets.sockets[client]

(yes, 2 times sockets)

Upvotes: 0

teamyates
teamyates

Reputation: 434

        var clients= io.sockets.adapter.rooms[room].sockets

Seems to do the trick!

Upvotes: 4

Quynh Nguyen
Quynh Nguyen

Reputation: 3009

You can use Socket Redis Adapter for manage SocketIO rooms.

const io = require('socket.io')(3000);
const redisAdapter = require('socket.io-redis');
io.adapter(redisAdapter({ host: 'localhost', port: 6379 }));

io.on('connection', function(client) {
    //Get allRooms by Redis Adapter
    io.of('/').adapter.allRooms((err, rooms) => {
        for (let room of rooms) {
             //Handle your room
        }
    })
})

Hope this help!

Upvotes: 0

Related Questions