Nodejs socket.io socket属性变为null

时间:2016-05-14 03:28:19

标签: node.js socket.io

所以我试图检索连接到房间的所有插座。但是我注意到,稍后在我的服务器脚本中访问时,将socket.username等套接字添加属性变为未定义。因此,我收到类似TypeError: Cannot read property 'username' of undefined的错误。我使用的是模块的1.3.3版本。

这是触发错误的代码

function clientsInRoom(room){
   var clients = [];
   console.log(io.sockets.adapter.rooms[room].length); // This prints out the correct number
   for(var cliSocket in  io.sockets.adapter.rooms[room] ){
        clients.push(io.sockets.connected[cliSocket].username); // Causes exception
   }
  return clients;
}

io.on('connection', function(socket){
   socket.on('adduser', function(username,room){
        // store the room name in the socket session for this client
        socket.room = room;
        // store the username in the socket session for this client
        socket.username = username;
        // Check if they already exist in room
        if(clientExists(username,room) == false){
            //Tell user they have joined new room
            socket.emit('updatechat','you have connected to '+ room);
            //echo to room that a person has connected to their room
            socket.broadcast.to(socket.room).emit('updatechat', username + ' has joined this room','con');
        }
        // send client to the room
        socket.join(socket.room);
        //Update online lists client side
        io.sockets.in(socket.room).emit('updatePeople', clientsInRoom(socket.room));

   });
});

如果有人能够解释这个问题,因为它一直让我感到疯狂,我将非常感激。

2 个答案:

答案 0 :(得分:1)

您正在迭代io.sockets.adapter.rooms的键。然后使用这些键访问io.sockets.connected。您从io.sockets.connected获得的内容未定义,而不是您保存的用户名。

检查此迭代代码,这就是问题所在。

答案 1 :(得分:0)

我的节点模块之间存在导致此问题的差异。从旧版本手动复制模块解决了问题