user309838
user309838

Reputation: 357

Nodejs socket.io - How to get all sockets and compare their properties?

I need to get all clients data and compare certain properties to determine who won the game

Code to give an example:

socket.on('joinedRoom', function(roomData){
    socket.join(roomData.roomname);
    socket.score = 0;
}):

and here I increment the player's score:

socket.on('sendPlayerScore', function(username){
    socket.score++;
});

So the idea is, I would get all scores from that specific room to determine who score more points.

Is there any good way to accomplish this?

Thanks!

Upvotes: 3

Views: 2350

Answers (2)

Cássio Lacerda
Cássio Lacerda

Reputation: 1634

In version 3, you can do it this way:

const email = "[email protected]";
const sockets = Array.from(await io.allSockets());
const found = array.find(
  (socketId) => io.sockets.sockets.get(socketId).email === email,
);

Where io.sockets.sockets.get(socketId).email, it's a socket previously set as socket.email = "[email protected]";

io.on("connection", async (socket) => {
  socket.email = "[email protected]";
});

Upvotes: 0

jfriend00
jfriend00

Reputation: 707158

You can see all the rooms and what socket IDs are in them with code like this:

let rooms = io.sockets.adapter.rooms;
for (let room of Object.keys(rooms)) {
    console.log("room");
    console.log("  ", rooms[room]);
}

io.sockets.adapter.rooms[room] will contain an object that has all the socket ids that are in that room like this:

{
    sockets: { 
        'm3wgTTKn-beT9TdyAAAB': true, 
        'mr-p1uL_jjeLzd0UAAAA': true 
    },
    length: 2 
}

And, given a socket.id, you can get the actual socket object from:

io.sockets.connected[id]

Putting it all together, you could enumerate all the sockets in a given room like this:

function getListOfSocketsInRoom(room) {
    let sockets = [];
    try {
        let socketObj = io.sockets.adapter.rooms[room].sockets;
        for (let id of Object.keys(socketObj)) {
            sockets.push(io.sockets.connected[id]);
        }
    } catch(e) {
        console.log(`Attempted to access non-existent room: ${room}`);
    }
    return sockets;
}

At this point, you have an array of sockets in the room so you can then run through that array to collect whatever info (e.g. score) you were looking for.

Upvotes: 2

Related Questions