Delais Delais - 1 month ago 9
AngularJS Question

Socket.IO - Send message to a specific user

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?

Answer

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

var sockets = {};

Now when a connection is established and you have a socket object you can authenticate your user and simply do

sockets[id] = socket;

Once you have a message you want to send to user with id you simply do

sockets[id].emit(...);

One 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.

Comments