'Django channel group_send all messages to one channel in the group
I am trying to make a real time chat web app with Django channel. When I am trying using Postman build multiple WS connections with it. I encountered some weird thing, let's say I have 2 connections to the same server at 8000 port. Then I send a message via group_send, ideally each connection will get 1 message, but it turn out 2 messages are send to the newer connection.
Here is my consumer:
class RealtimeConsumer(AsyncJsonWebsocketConsumer):
async def websocket_connect(self, event):
user_id = self.scope['user']
await self.channel_layer.group_add(
str(user_id), # use id as the group name
self.channel_name
)
await self.accept()
await self.send_json(
{
"connectionKey": self.channel_name,
"clientId": str(user_id),
},
)
async def send_message(self, event):
message = event["message"]
await self.send_json(
{
"messages": message,
"connectionKey": self.channel_name,
},
)
async def websocket_disconnect(self, message):
user_id = self.scope['user']
await self.channel_layer.group_discard(
str(user_id), # group name
self.channel_name
)
Send to group func:
def send_single_user_msg(channel_name, message):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.send)(
channel_name, {
'type': 'send_message',
"text": message,
}
)
I'm using local redis server as the channel layer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
