Suppose I have the following Schema in MongoDB:
var postSchema = new mongoose.Schema({
owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
contributors: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
});
Every Post must have an owner and may have many contributors (added by the owner).
When the owner or any of the contributors makes a change to the post object, I need to notify that change to all of the associated users, in real-time (using Socket.IO).
But I'm having some doubts of how to do this... I mean, I know that Socket.IO has some methods to emit a message to a specific user but we need to know the SocketID. How can I associate the UserID with the SocketID? Can I add it as property and then traverse all the sockets to find the socket with the required UserIDs? But wouldn't this take too much time if we had many sockets connected to the server?
Normally you would use a hashmap (i.e. an object in JavaScript) of the form
{id: socket}
or{id: [sockets]}
if you support multiple connections from one user.For example
Now when a connection is established and you have a
socket
object you can authenticate your user and simply doOnce you have a message you want to send to user with
id
you simply doOne thing you have to remember about is to remove sockets from
sockets
object once they are disconnected otherwise you'll have a memory leak.All of that is assuming you are dealing with only 1 real-time server. The complexity rises very high if you are dealing with a distributed environment but I suppose that's not your issue at the moment.
SURE: Simply,
This is what you need :
whenever a user joined to the server,socket details will be generated including ID.This is the ID really helps to send a message to particular people.
first we need to store all the socket.ids in array,
here name is the reciever name. Example:
So, now we can get that socket.id with the reciever name whenever we are sending message:
for this we need to know the recievername.You need to emit reciever name to the server.
final thing is:
Hope this works well for you.!!Good Luck