Socket.IO-向特定用户发送消息 [英] Socket.IO - Send message to a specific user

查看:1611
本文介绍了Socket.IO-向特定用户发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在MongoDB中具有以下架构:

var postSchema = new mongoose.Schema({
  owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  contributors: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
});

每个帖子必须具有所有者,并且可能有许多贡献者(由所有者添加).

当所有者或任何贡献者对post对象进行更改时,我需要将该更改实时通知给所有关联的用户(使用Socket.IO).

但是我对如何执行此操作有疑问...我的意思是,我知道Socket.IO有一些向特定用户发送消息的方法,但是我们需要知道SocketID.如何将UserID与SocketID关联?我可以将其添加为属性,然后遍历所有套接字以查找具有所需UserID的套接字吗?但是,如果我们将许多套接字连接到服务器,这会不会花费太多时间?

解决方案

如果您支持一个用户的多个连接,通常您将使用格式为{id: socket}{id: [sockets]}的哈希映射(即JavaScript中的对象). /p>

例如

var sockets = {};

现在,当建立连接并且您拥有一个socket对象时,您可以对用户进行身份验证并只需执行

sockets[id] = socket;

一旦您想通过id发送给用户的消息,您只需完成

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

您要记住的一件事是,一旦断开连接,请从sockets对象中删除套接字,否则会发生内存泄漏.

所有这些都假设您仅在处理1台实时服务器.如果您要处理分布式环境,则复杂性会非常高,但是我认为目前这不是您的问题.

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

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.

这篇关于Socket.IO-向特定用户发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆