Saturday 10 June 2017

Build array of connected hosts in socket.io - Replace object by key value

I have simple problem when in socket.io Im trying to build array of connected hosts - to send specific information to them. The problem is not in socket.io but in building object passed to emit().

This script checks host type, and then pushing his "socket.id" to array. But when i push new host data , it replaces all objects in array. Not only his instance. I tried other structure of object (with socket.id as key), but only this object is passed to emit() properly. But with that notation of object I have problem with replacing values. I tried building JSON object and only javascript object works. I was doing stringify , encode decode JSON without success.

admins = [];
clients = [];


socket.on('add-user', function (data) {

    if (data.type === "admin") {
       var adminHost = new Object();
        adminHost.id = socket.id;
        adminHost.username = data.username;
        adminHost.location = data.location;

        admins.push(adminHost);

                       for (key in admins) {
                        console.log('check if exist');

                       if (admins[key].id === socket.id) {
                           admins.splice(key,1);
                           // admins[key].username = data.username;
                           // admins[key].location = data.location;
                           admins.push(adminHost);

                       }else{
                       }
                         //  admins.push(adminHost);
                   }
        console.log(admins);
    }
});

This is function to emit() by socket.io. I know that this part would not work without proper key that should have value of socket.id , but this is not the problem.

 function emitClientsData() {
 if (!admins) {
    console.log('No admins on dashboards   :::::');
} else {

    for (key in admins) {
        console.log("Panels ::::: " + admins[key]);
        io.to(key).emit('daneSerwerow', admins);
    }
}
}

setInterval(emitClientsData, 5000); 

The problem is that on all connection made by add-user, another object is pushed to admins array. not replaced existing one instance. If i will connect second host as admin in dashboard , all objects are replaced to new values- not two different hosts.

 [ { id: 'cak8CkxCGH8m7R5qAAAB', username: 'aaa', location: 'root' },
 { id: 'cak8CkxCGH8m7R5qAAAB', username: 'aaa', location: 'root' },
 { id: 'cak8CkxCGH8m7R5qAAAB', username: 'aaa', location: 'root' },
 { id: 'cak8CkxCGH8m7R5qAAAB', username: 'aaa', location: 'root' },
 { id: 'cak8CkxCGH8m7R5qAAAB', username: 'aaa', location: 'root' } ]



via Zbigniew Adam Karski

No comments:

Post a Comment