I have a websocket that receives a token as a query string. My custom middleware then decodes this token to find the username passed through this token.
The current user connecting to the websocket is then subscribed to a group named after their user_id. Let's assume UserA goes through this process initially and they are subscribed to group '1'
UserB then connects to the websocket following the same process. At this point I assume there are two groups; one named '1' and another names '2'.
Upon UserA triggering the send & receive method in the frontend, I have a consumer function that sends a message to the group with the user_id it receives ('2').
However, when this code runs, I don't seem to be sending a message to any group. I am not getting any error message (I can see the message I want to send being printed on my terminal).
However when I open two browsers; one with UserA and the other with UserB, when I connect to the websocket and trigger send/receive I don't see the message I am sending being console logged on either browsers.
Here is the code for the consumer class handling the connect, send and receive methods:
class PracticeConsumer(AsyncConsumer):
async def websocket_connect(self, event):
username = self.scope['user']
username_id = str(await self.get_user(username))
await self.channel_layer.group_add('{}'.format(username_id), self.channel_name)
await self.send({"type": "websocket.accept", })
async def websocket_receive(self, event):
received = event["text"]
user_and_id = received.split()
username = user_and_id[0]
user_id = str(await self.get_user(username))
sleep(1)
await self.channel_layer.group_send(
'{}'.format(user_id),
{
"type": "send.message",
"message": "!!!!the websocket is sending this back!!!!",
},
)
async def websocket_disconnect(self, event):
print("disconnected", event)
async def send_message(self, event):
message = event['message']
self.send({
'message': message
})
@database_sync_to_async
def get_user(self, user_id):
try:
return User.objects.get(username=user_id).pk
except User.DoesNotExist:
return AnonymousUser()