问题
I want to send notification to specific authenticated user using Channels 2.
In below code i am sending notification as a broadcast instead of that i want to send notification to a specific user.
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}")
回答1:
Most users new to Django-channels 2.x face this problem. let me explain.
self.channel_layer.group_add("gossip", self.channel_name)
takes two arguments: room_name and channel_name
When you connect from your browser via socket
to this consumer, you are creating a new socket connection called as channel
. So, when you open multiple pages in your browser, multiple channels are created. Each channel has a unique Id/name : channel_name
room
is a group of channels. If anyone sends a message to the room
, all channels in that room
will receive that message.
So, if you need to send a notification/message to a single user, then you must create a room
only for that particular user.
Assuming that current user
is passed in the consumer's scope
.
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
)
Whenever you send/broadcast a message to user_room_name
, It will only be received by that user.
来源:https://stackoverflow.com/questions/55310717/sending-notification-to-one-user-using-channels-2