I am trying to store all connected sockets in an array like `
var basket = {};
io.sockets.on('connection', function (socket) {
socket.on("register", function(user_profile) {
basket[user_profile.id] = socket.id;
});
socket.on(SEND_INVITE,function(invitation_details){
var to = basket[invitation_details.invitee];
io.sockets.socket(to).emit(RECIEVE_INVITE,invitation_details);
});
});
`
But i dont know whats wrong in the code, only last joined client is getting stored in baskets. Help me please
This is how i've done it in a project I created. I've used the username as the key, and the socket.id as the value. Then in the clients hash I've used the socket.id as the key, and the socket as the value. This allows me to quite easily emit a message to a 'valid' user, based on their username.
var validUsers = {};
var clients = {};
io.sockets.on('connection', function (socket)
{
var hs = socket.handshake;
if(hs.session)
{
if(hs.session.username)
{
clients[socket.id] = socket; // add the client data to the hash
validUsers[hs.session.username] = socket.id; // connected user with its socket.id
}
}
...
clients[validUsers[username]].emit('move-story', data);
}
//Auth the user
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionID = data.cookie['express.sid'];
//Save the session store to the data object
data.sessionStore = sessionStore;
sessionStore.get(data.sessionID, function(err, session){
if(err) throw err;
if(!session)
{
console.error("Error whilst authorizing websocket handshake");
accept('Error', false);
}
else
{
console.log("AUTH USERNAME: " + session.username);
if(session.username){
data.session = new Session(data, session);
accept(null, true);
}else {
accept('Invalid User', false);
}
}
})
} else {
console.error("No cookie was found whilst authorizing websocket handshake");
return accept('No cookie transmitted.', false);
}
});