Socket IO 默认房间

Socket IO Default Rooms

我想在 Python 中使用 Web Socket 创建一个实时通知中心。 我有一个向特定用户发送/发出消息的功能。

我已阅读有关插座 ID 和房间的信息。我认为有几种方法可以使用 Socket IO 的两个功能进行直接用户交互。

第一个:

文档中说,每个连接到套接字服务器的客户端/套接字,它们都会提供一个唯一的套接字#id,并加入一个由 id 标识的房间。 我有一个想法,我不需要为用户再次创建一个房间,只需使用这个默认房间即可。

通过使用这些,我想创建一个 socket#id 与 userid(登录的用户 id)的映射,并将其存储到 redis 中。比如,如果我想向用户 ID 发送消息,我只需要搜索它的 socket#id。

The question for this first way is, is the socket#id will be the same if a client disconnect and reconnect soon the connection can be established ?

第二个:

我已经阅读了很多有关使用聊天室发送私信的资料。对于连接的客户端或套接字,我只需要创建一个新房间,其 ID 为从客户端发送的用户 ID(用户登录后)。

这种方式的优点是,如果用户在多个设备上使用相同的用户 ID,我可以将他们分组在一个房间中。所以,如果我想通知所有设备,我只需要发送id用户房间的消息。

The question of this way, is the user will be moved from default room from first way or they will be on 2 room (1 default, 1 specified room by user id) ?

谢谢

我就是这样做的

一个用户的 socketid 在每个页面请求中都会不同,如果一个用户打开了 3 个选项卡,他在每个选项卡上都会有一个不同的 socketid,所以如果你想让用户在每个选项卡中都收到通知,你需要发送到 3 个 socketids

一个解决方案是创建一个连接用户的对象,您可以将 userid/username 作为键添加到您的对象中,并为该用户创建一个包含所有 socketid 的数组,确保删除 socketid当用户也断开连接时,当你想发送通知时,你只需遍历数组并发送给所有用户 socketids

The question for this first way is, is the socket#id will be the same if a client disconnect and reconnect soon the connection can be established ?

没有。每个连接都有一个随机分配的套接字 ID。

The question of this way, is the user will be moved from default room from first way or they will be on 2 room (1 default, 1 specified room by user id) ?

用户可以同时在多个房间。如果您使用应用程序生成的用户 ID 创建一个房间,然后将用户的所有套接字连接放入该房间,则这些客户端中的每一个都将在两个房间中,一个与套接字 ID 匹配,一个与您的用户匹配ID。然后,您可以单独向每个套接字或属于用户的所有套接字发送消息。