我正在尝试在socket 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”是“[]”(空?),因此“客户”是“未定”。 我做错了什么?
如果用户是连接的,则来自服务器的控制台日志的值为1。如果有更多用户在线,那么它仍然是1,但至少它应该将此值发送给客户端。
由于
答案 0 :(得分: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 ...
答案 1 :(得分:0)
甚至已经解决了。
问题是:io.sockets.clients(room)只计算接受网络摄像头访问权限的用户,否则房间里的“真的”不是。
问候