我想使用通道2向特定的经过身份验证的用户发送通知。在
在下面的代码中,我以广播的形式发送通知,而不是我要向特定用户发送通知。在
from channels.generic.websocket import AsyncJsonWebsocketConsumer
class NotifyConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
await self.channel_layer.group_add("gossip", self.channel_name)
print(f"Added {self.channel_name} channel to gossip")
async def disconnect(self, close_code):
await self.channel_layer.group_discard("gossip", self.channel_name)
print(f"Removed {self.channel_name} channel to gossip")
async def user_gossip(self, event):
await self.send_json(event)
print(f"Got message {event} at {self.channel_name}")
大多数刚接触Django channels 2.x的用户都面临这个问题。让我解释一下。在
self.channel_layer.group_add("gossip", self.channel_name)
有两个参数:房间名称和频道名称当您通过
socket
从浏览器连接到此使用者时,您正在创建一个名为channel
的新套接字连接。因此,当您在浏览器中打开多个页面时,会创建多个频道。每个通道都有一个唯一的Id/名称:channel_name
room
是一组通道。如果有人向room
发送消息,room
中的所有通道都将接收该消息。在因此,如果需要向单个用户发送通知/消息,则必须仅为该特定用户创建
room
。在假设当前的
user
在消费者的scope
中传递。在每当您向
user_room_name
发送/广播消息时,它将只由该用户接收。在相关问题 更多 >
编程相关推荐