NodeJs socket.io让所有客户都在房间里

时间:2017-01-07 08:19:09

标签: javascript node.js sockets socket.io

使用io.sockets.adapter.rooms[room]在这个下面的函数我可以获得特殊房间的所有套接字ID,现在我正在尝试将套接字ID作为房间客户端,但不幸的是我在{{1}上得到undefined当我尝试在socketIds[i]

上使用它时

例如:

clients.push(chatClients[socketIds[i]]);

如何使用socketIds:{"sockets":{"yJJj6ysKEPp0UhOdAAAA":true,"9dDHXedsMRrjJNhrAAAB":true},"length":2} sockets获取所有socketIds

length

1 个答案:

答案 0 :(得分:0)

此代码解决的问题

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;
}