How to get the key from value in key/value pair in

2019-07-10 20:25发布

I am storing username/SocketID pairs in redis store for my socket.io chat application.

When the user disconnects i need to remove the username/socketID pair from the redis store. I have seen how to get the value from a key but never a key from a value. Is it possible? or either way how can i delete the key/value pair from just the value. Here's my code

For adding to store on connect

socket.on('username', function (username) {

    client.set(username, socket.id, function (err) {
        console.log(username + ":" + socket.id);
    });

});

For disconnect, the client wont know when the disconnect will happen, might happen due to loss of internet connectivity but when the socket disconnects it always hits the "disconnect" event. In this event i need to delete the username/socketID pair.

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

// dont know the username??

    client.del(username, socket.id, function (err) {
        if (err)
            console.log(err);
        else {
            socket.disconnect();
            console.log(socket.id + " DISCONNECTED");
        }
    });
});

2条回答
一夜七次
2楼-- · 2019-07-10 20:42

I would suggest that you incorporate the socket.io Id into the key e.g.

id:username

Then you could do something like this

client.keys([socket.id + ':*'], function (err, result) {
    if (err){
        //handle in some way
    }

    for (var r in result) {
        var key = result[r];

        client.del(key, function(err, result){
            // handle in some way
        });
    }
});
查看更多
【Aperson】
3楼-- · 2019-07-10 20:51

The easiest way is to store two pairs. One with username/id and one with id/username. So whatever information you have, you can get the other and as a result the other key/value pair too.

查看更多
登录 后发表回答