NodeJS Chat:存储用户名

时间:2014-01-26 16:51:00

标签: node.js chat

我正在与NodeJS建立聊天,但它不会将用户名存储在var用户中:

// chat sockets
var io = require('socket.io').listen(3872, { log: false });
var users = [];
io.sockets.on('connection', function (socket) {

    socket.on('requestUsername', function(username) {
        socket.username = escape(username.value);
        users.push({
            username: username.value
        });
        console.log(username.value + " joined the chat. "+ users.length +" chatters online now!");
        console.log(users);
    });

    socket.on('disconnect', function() {
    });
});

所以,当有人加入时,例如:史蒂夫,var用户是:{用户名:'史蒂夫'},但是当西蒙加入时:{用户名:'西蒙'}和史蒂夫现在离开用户var?为什么?以及如何解决它?

1 个答案:

答案 0 :(得分:0)

修正:

// chat sockets
var io = require('socket.io').listen(3872, { log: false });
var users = [];
io.sockets.on('connection', function (socket) {

    socket.on('requestUsername', function(username) {
        socket.username = escape(username.value);
        users.push(username.value);
        console.log(username.value + " joined the chat. "+ users.length +" chatters online now!");
        console.log(users);
    });

    socket.on('disconnect', function() {
    });
});

我不知道为什么会这样做?