3

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())
]
Ngo Van
  • 857
  • 1
  • 21
  • 37
  • Can you please also share your `routing.py` file content. I.e. urlpatterns where `ZzConsumer` registered? – Egor Wexler Jun 26 '22 at 10:23
  • Is `chat_message` getting triggered? Try to replace `'type':'chat_message'` with `'type':'chat.message'`. – Taras Mykhalchuk Jun 26 '22 at 10:39
  • @EgorWexler I updated the Question. @TarasMykhalchuk the `chat_message` not triggered. Let me try change the `type` and check again – Ngo Van Jun 26 '22 at 10:48

1 Answers1

4

I think you're missing type argument in chat_message method. It should match the type in group_send. I.e.:

    def chat_message(self, event, type='chat_message'):
        print("EVENT TRIGERED")

Matches:

async_to_sync(channel_layer.group_send)(
    'test',
    {
        'type': 'chat_message',
        'message': "event_trigered_from_views"
    }
) 
Egor Wexler
  • 1,754
  • 6
  • 22
  • instead of group send is there any clean way to support sending the event only to a particular user ? Some methods which i know are making user level groups, excluding some users when the function is being called etc is there any way we can send the event to the user alone ? – Jay Jain Jul 03 '23 at 07:09