简体   繁体   中英

NodeJs socket.io get all clients on room

with io.sockets.adapter.rooms[room] on this below function i can get all socket id of special room, now i'm trying to push socket id as room clients, but unfortunately i get undefined on socketIds[i] when i try to use that on clients.push(chatClients[socketIds[i]]);

for example:

socketIds:{"sockets":{"yJJj6ysKEPp0UhOdAAAA":true,"9dDHXedsMRrjJNhrAAAB":true},"length":2}

how can i get all sockets from socketIds with using length ?

function getClientsInRoom(socketId, room) {
    // get array of socket ids in this room
    var socketIds = io.sockets.adapter.rooms[room];
    console.log("socketIds:" + JSON.stringify(socketIds));
    var clients = [];

    if (socketIds && socketIds.length > 0) {
        //socketsCount = socketIds.lenght;

        // push every client to the result array
        for (var i = 0, len = socketIds.length; i < len; i++) {

            // check if the socket is not the requesting
            // socket
            if (socketIds[i] != socketId) {
                clients.push(chatClients[socketIds[i]]);
            }
        }
    }

    return clients;
}

problem resolved by this code

function getClientsInRoom(socketId, room) {
    // get array of socket ids in this room
    var socketIds = io.sockets.adapter.rooms[room];
    var clients = [];

    if (socketIds && socketIds.length > 0) {
        //socketsCount = socketIds.lenght;

        // push every client to the result array
        for (var i = 0, len = socketIds.length; i < len; i++) {
            // check if the socket is not the requesting
            // socket
            if (socketIds.sockets[i] != socketId) {
                clients.push(chatClients[Object.keys(socketIds.sockets)[i]]);
            }
        }
    }

    return clients;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM