Socket.IO - Send message to a specific user

2019-08-06 10:13发布

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?

2条回答
干净又极端
2楼-- · 2019-08-06 10:46

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-08-06 11:02

SURE: Simply,

This is what you need :

  io.to(socket.id).emit("event", data);

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,

 var people={};

 people[name] =  socket.id;

here name is the reciever name. Example:

 people["ccccc"]=2387423cjhgfwerwer23;

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:

 socket.on('chat message', function(data){
 io.to(people[data.reciever]).emit('chat message', data.msg);
 });

Hope this works well for you.!!Good Luck

查看更多
登录 后发表回答