获取socket.io和node.js中当前连接的用户名

时间:2013-11-15 03:28:50

标签: javascript node.js sockets

嗨,大家有一个问题,如何从套接字AddUsers获取所有用户并将其转移到套接字get winners?我试图直接将它调用到该功能,但它确实显示出来..我需要将它保存到cookie中吗?

var usernames = [];
io.sockets.on('connection', function (socket){



     socket.on('addUsers', function (data) {

     var users   = {
         data : data.box,
         socket_id : socket.id
     }

      socket.username = data.username;
          usernames.push({username : data.username, itemid : data.itemid,  box : data.box,socket_id : socket.id});

         socket.emit('displayUsers', {users: usernames});
     });


     socket.on('get winners', function (data) {
     socket.emit('display winners', {data: usernames});

     });




});

1 个答案:

答案 0 :(得分:0)

只需声明另一个变量即可:

var usernames = [];
var sockets = {};
io.sockets.on('connection', function (socket){
    sockets[socket.id] = socket;
    socket.on('addUsers', function (data) {
        ...
    }
}

就是这样。如果要使用它,只需键入“sockets [yourSocketId] .emit()”