【问题标题】:Socket.IO transmitting a array per emit(...)Socket.IO 每发射一个数组(...)
【发布时间】:2013-03-28 23:31:25
【问题描述】:

我正在尝试在我的套接字 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,但至少它应该将此值发送给客户端。

谢谢

【问题讨论】:

    标签: javascript node.js sockets webrtc


    【解决方案1】:

    我终于解决了:

     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...

    【讨论】:

    • "for (var room in roomList)" 是循环的意思。但是console.log 只是后来才使用的。抱歉,如果这让您感到困惑。我应该在循环结束后直接记录它。
    【解决方案2】:

    就算解决了。

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

    问候

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 2014-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多