2017-11-11 167 views
0

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

[ {xPos: 13, yPos: 42, name: "Example1"}, {xPos: 32, yPos: 53, name: "Example2"} ]

也,我不是母语,我的英语可能是太可怕了。

回答

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]; 
}) 
+0

非常感谢! –

+0

我得到的错误:ACTIVE_USERS.push不是函数 –

+0

@Pitr_我的不好,已经更新了答案 –