I am using Django Channels to receive the message from the user and send it back to the same user. I use the following codes for this:
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.sender = self.scope['url_route']['kwargs']['username']
self.group_name = f'sample_{self.sender}'
self.channel_layer.group_add(
self.group_name, self.channel_name
)
self.accept()
def disconnect(self, close_code):
self.channel_layer.group_discard(
self.group_name, self.channel_name
)
def receive(self, text_data=None, bytes_data=None):
text_data_json = json.loads(text_data)
message = text_data_json["message"]
self.channel_layer.group_send(
self.group_name, {"type": "chat_message", "message": message}
)
print('receive')
def chat_message(self, event):
print('chat message')
message = event["message"]
self.send(text_data=json.dumps({"message": message}))
When a request is made to the socket, the following is displayed in the terminal:
HTTP GET /send-sample/majidi 200 [0.01, 127.0.0.1:61693]
WebSocket DISCONNECT /ws/sample/majidi/ [127.0.0.1:61695]
WebSocket HANDSHAKING /ws/sample/majidi/ [127.0.0.1:61702]
WebSocket CONNECT /ws/sample/majidi/ [127.0.0.1:61702]
receive
In fact, in these codes, the chat_message function is not executed and “chat message” it is not printed. And finally, the message is not sent to the user.
What is the problem with these codes?