如何更改套接字的ID?

时间:2017-07-23 09:53:43

标签: node.js socket.io

我在node.js中创建了一个应用程序,我注意到每次用户打开新页面或更改页面时,都会获得不同的套接字ID。是否可以更改该套接字的id,以便用户始终具有相同的套接字ID? 当用户连接到服务器时,它会在mongodb中保存uid和套接字的id,并在每次连接时获取该数据。

这是我的代码:

nspm.on('connection', function(socket) {
        db.c_oneusr(socket.decoded_token, function(err, docs){
            if(docs) {
                if(docs.ban=='1') {
                    nspm.to(socket.id).emit('ckusr', 'banned');
                    socket.disconnect();
                    return;
                }
                else {
                    nspm.to(socket.id).emit('ckusr', 'ok');
                    if (!docs.laston) {
                        docs.laston = 0;
                    }
                    initializeConnection(socket, docs.laston);
                }
            }
            else {
                nspm.to(socket.id).emit('ckusr', 'ok');
                initializeConnection(socket, 0);
            }
        });
    });

    function initializeConnection(socket, laston){
        var online = [];
        laston = new Date(laston);
        socket.uid = socket.decoded_token.uid;
        socket.buddies = socket.decoded_token.buddies;
        // id contains all ids of each user
        if (!id[socket.uid]) {
            id[socket.uid] = {};
        }
        id[socket.uid][socket.id] = 1;
        socket.join(socket.uid);
        for (var buddy in socket.buddies) {
            var buddy_id = socket.buddies[buddy];
            socket.join(buddy_id);
            if (uidlist[buddy_id]) {
                online.push(parseInt(buddy_id, 10));
            }
        }
        socket.emit('login', {
            online: online
        });
        socket.broadcast.to(socket.uid).emit('user joined', {
            uid: socket.uid
        });
        data = [];
        data["uid"] = socket.decoded_token.uid;
        data["id"] = socket.id;
        db.updpml(data); // Update user data
    }

0 个答案:

没有答案