使用通道 2 向一位用户发送通知

sending notification to one user using Channels 2

我想使用通道 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 的用户都会遇到这个问题。让我解释一下。

<b>self.channel_layer.group_add("gossip", self.channel_name)</b> 接受两个参数:room_namechannel_name

当您通过 socket 从浏览器连接到此消费者时,您正在创建一个名为 <b>channel</b>[=46= 的新套接字连接].因此,当您在浏览器中打开多个页面时,会创建多个渠道。每个频道都有一个唯一的 Id/name : <code><b>channel_name</b>

<b>room</b>是一组频道。如果有人向 <b>room</b> 发送消息,则该 room[ 中的所有频道=46=] 将收到该消息。

因此,如果您需要向单个用户发送 notification/message,那么您必须仅创建一个 <b>room</b>对于该特定用户。

假设当前user在消费者scope中传递。

<b>self.user = self.scope["user"]
self.user_room_name = "notif_room_for_user_"+str(self.user.id) ##Notification room name
await self.channel_layer.group_add(
       self.user_room_name,
       self.channel_name
    )</b>

每当您 send/broadcast 向 user_room_name 发送消息时,它只会被该用户接收。