I am currently using Node.js
and it's working very well, for each user I save sockets. also saving all browser tab sockets ID. I mean each tab has a unique socket. so a unique user have multiple sockets. Here is what I do.
usersObj = {};
io.sockets.on( 'connection', function( socket ) {
socket.on("new user", function( data, callback ) {
if ( data.id in usersObj ){ // if user is in usersObj, save it's new socket.id
usersObj[data.id].sockets_ids.push( socket.id );
// how to send a message to all sockets of a specific user
// usersObj[data.id].sockets.socket.emit( "hi", { data: "Hi!" } ); this does not work.
} else { // if user is not in usersObj, make a new object and save it's socket.
usersObj[data.id] = {
"sockets_ids" : [ socket.id ] // array for all sockets id of this user
}
}
});
});
Now userObj for user with ID 10, and user with ID 11, is this:
usersObj = {
10 = {
sockets_ids = [
asdf9877687sdfasdf, // sample socket ID for browser tab 1
459djhfskdhjfasd8f, // sample socket ID for browser tab 2
oewurwoer845935739 // sample socket ID for browser tab 3
]
},
11 = {
sockets_ids = [
xcdf987sdfsddfasdf, // sample socket ID for browser tab 1
ty9djhfskdhjf45344, // sample socket ID for browser tab 2
sawurwoer84593xcvx // sample socket ID for browser tab 3
]
},
}
Now I want to emit a message Hi!
to all sockets belongs to user with ID 10.
So I should get sockets by their ID which is in user's sockets_ids array and emit to that socket my message.
How can I do that?
This is completely wrong and does not work.
usersObj[data.id].sockets_ids.socket.emit( "hi", { data: "Hi!" } );
Thanks in advance.