jovan jovan - 4 months ago 37
Node.js Question

One-line check if socket is in given room?

I'm using Node.js with socket.io for a multiplayer card game, and there are game rooms which players can join.

For joining a room, I simply use:

io.sockets.on('connection', function (socket) {
socket.on('joinRoom', function (gid) {
//gid is game ID - create room name based on this and join the room
var room = 'game'+gid;
socket.join(room);
});
});


My question is, what is the quickest way to check if a socket is connected to a certain room? I know I could get all sockets in that room in an array and then check whether the target socket is in the array, but I'm guessing there should be a more basic syntax for this. What I'm looking for (in pseudo-code) would be

if(socket with ID "z8b7dbf98i" is in room "game10")
//do something

Answer

For the documentation, socket.io doesn't seem to have any simple way to do that. You really need to check if the client is in the room array, or the opposite: if the room is in the client array.

This can be done with an oneliner using indexOf:

if(socket.rooms.indexOf(room) >= 0)

Or the opposite search:

if(io.sockets.manager.rooms['/' + room].indexOf(socket.id) >= 0)
Comments