I'm new in Python and Django,
Currently, I need to setup a WebSocket server using Channels.
I follow the code in this link: Send message using Django Channels from outside Consumer class
setting.py
ASGI_APPLICATION = 'myapp.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}
Here is the code Consumer
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class ZzConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'test'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
print("DISCONNECED CODE: ",code)
def receive(self, text_data=None, bytes_data=None):
print(" MESSAGE RECEIVED")
data = json.loads(text_data)
message = data['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
"type": 'chat_message',
"message": message
}
)
def chat_message(self, event):
print("EVENT TRIGERED")
# Receive message from room group
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'type': 'chat',
'message': message
}))
And outside the Consumer:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'test',
{
'type': 'chat_message',
'message': "event_trigered_from_views"
}
)
The expected logics is I can received the data from the group_send
in the receive
on the Consumer class. So that I can send message to client.
However, It's not.
Can anyone here know what's I missing?
Any help is very appreciated.
Thanks!
Updated:
routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/socket-server/', consumers.ZzConsumer.as_asgi())
]