1

我正在尝试在我的套接字 io 服务器中构建一个数组并将其发送到客户端。

 var roomList = io.sockets.manager.rooms;

    // new Array to save the clients per room
    var clientsPerRoom = new Array();

    //for (var i = 0; i < roomList.length; i++) {
    for (var room in roomList) {
        room = room.replace("/", "");

        // get the clients per room
        var clients = io.sockets.clients(room).length;

        // saving it in the array at the name of the room
        clientsPerRoom[room] = clients;
    }
    // transmit it to the client
    io.sockets.emit('roomList', roomList, clientsPerRoom);

在客户端

var clients = 1;

        for (room in roomList) {
            if (room.length > 0) {
                room = room.replace("/", "");

                clients = clientsPerRoom[room];

                console.log("ROOM: '" + room + "' has '" + clients + "' CLIENTS");

            }
        }

在客户端,“clientsPerRoom”是“[]”(空?),所以“clients”是“未定义的”。我究竟做错了什么?

在来自服务器的控制台日志中,如果用户是连接的,则值为 1。如果有更多用户在线,那么它仍然是 1,但至少它应该将此值发送给客户端。

谢谢

4

2 回答 2

0

最后我解决了它:

 var clients = io.sockets.clients(room).length;
            // has to look like this:
            //clientsPerRoom = {"test" : 3, "xyz" : 4};
            clientString = '"' + room + '" : "' + clients + '",' + clientString;

            console.log("clientsPerRoom[" + room + "] : " + clientsPerRoom[room]);
            console.log("__END OF LOOP__");
        }
    }
    //cut the "," et the end of the string (else: ERROR!)
    clientString = clientString.substr(0, clientString.length-1);
    // parse it with JSON to pretend beeing a object
    clientsPerRoom = JSON.parse('{' + clientString + '}');

    // now send it to the client
    io.sockets.emit('roomList', roomList, clientsPerRoom, totalClients);

现在另一个问题是,

var clients = io.sockets.clients(room).length;

总是 1...

于 2013-03-28T14:02:52.413 回答
0

即使解决了。

问题是:io.sockets.clients(room) 只计算接受网络摄像头访问的用户,否则他们还不是“真正”在房间里。

问候

于 2013-03-28T15:31:25.393 回答