Question

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");
        }
    });
});
Était-ce utile?

La solution

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.

Autres conseils

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
        });
    }
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top