Sunday, 12 March 2017

Check if friend is online

I'm creating a messaging web app similar to whatsapp with Socket IO, but I'm having a problem with detecting if the user that is in my contact list is online or offline.

I have implemented a function called "new user" where every time a new client connects to the server it will add them to an array and then broadcast it to all clients after that the client loops through all the array and checks which one is in its contact list to determine if its online or not.

The problem is that imagine if there are 50.0000 users connecting and disconnecting. All clients would have to update and compare all online users with their contact list each time. That sounds like a really inefficient way to do it.

Any ideas?

Server:

socket.on('new user', function(data, callback) {

    if (data in nicknames) {
        callback(false);
    } else {
        callback(true);
        socket.nickname = data;
        nicknames[socket.nickname] = 1;
        console.log("connected "+socket.nickname);
        updateNickNames();  
    }
});

socket.on('disconnect', function(data) {
    if(!socket.nickname) return;
    delete nicknames[socket.nickname];
    console.log("disconnected "+socket.nickname);
    updateNickNames();

});

function updateNickNames() {
    io.sockets.emit('usernames', nicknames);
}

Client:

socket.on('usernames', function(data) {
    for (var username in data) {
        for(var i = 0; i < contactList.length; i++) {
            if(username == contactList[i]){
                alert("user "+contactList[i]+" online");
            }
        }
    }
});



via Armando Alain GutierrezdeVelas

No comments:

Post a Comment