簡體   English   中英

NodeJs socket.io讓所有客戶都在房間里

[英]NodeJs socket.io get all clients on room

io.sockets.adapter.rooms[room]在這個下面的功能我可以獲得特殊房間的所有套接字ID,現在我正在嘗試將套接字ID作為房間客戶端,但不幸的是我在socketIds[i]上得到undefined當我嘗試在clients.push(chatClients[socketIds[i]]);上使用它clients.push(chatClients[socketIds[i]]);

例如:

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

如何使用lengthsocketIds獲取所有sockets

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

此代碼解決了問題

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM