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