socket.io如何制作自定义用户列表

时间:2017-11-11 10:46:37

标签: javascript node.js sockets socket.io

如何创建连接到nodejs socket.io服务器的自定义用户列表?通过自定义,我的意思是每个用户都有xPos,yPos,name这样的属性。所以列表看起来像这样

FB.ui

另外,我不是母语,我的英语可能很糟糕。

1 个答案:

答案 0 :(得分:0)

// Index users by socket id
var ACTIVE_USERS = {};

io.on('connection', function(socket) {
  socket.on('NEW_USER', function(user) {
    // Here user can have your custom properties (xPos, yPos, etc) that can be passed in from the client
    ACTIVE_USERS[socket.id] = user;
  })

  socket.on('disconnect', function() {
    delete ACTIVE_USERS[socket.id];
  });
});

// You can get active users as an array this way
var users = Object.keys(ACTIVE_USERS).map(function(key) {
  return ACTIVE_USERS[key];
})