Home > Blockchain >  How to call another websocket function in django channels consumer functions?
How to call another websocket function in django channels consumer functions?

Time:10-27

I have following code in consumers.py

from channels.consumer import SyncConsumer
from asgiref.sync import async_to_sync

class EchoConsumer(SyncConsumer):
    def websocket_connect(self,event):
        self.room_name = 'broadcast'
        self.send({
            'type':'websocket.accept'
        })
        async_to_sync(self.channel_layer.group_add(self.room_name, self.channel_name))
        print(f'[{self.channel_name}] - you are connected')

    def websocket_receive(self,event):
        print(f'[{self.channel_name}] - Recieved message - {event["text"]}')
        async_to_sync(self.channel_layer.group_send)(
            self.room_name,
            {
                'type': 'websocket.message',
                'text': event.get('text')
            }
        )

    def websocket_message(self,event):
        print(f'[{self.channel_name}] - message Sent - {event["text"]}')
        self.send({
            'type':'websocket.send',
            'text':event.get('text')
        })
    
    def websocket_disconnect(self,event):
        print(f'[{self.channel_name}] - disconnected')
        print('connection is disconnected')
        async_to_sync(self.channel_layer.group_discard(self.room_name, self.channel_name))
    

I want to call the message function whenever a message is recieved so in websocket_recieve function I have addes 'type': 'websocket.message', but I don't know why websocket_message function is not being called?

I am new to django channels.Message is receieving successfully from any connection but not sending to any connection.

any help will be appreciated.

CodePudding user response:

change the websocket_connect function to this

def websocket_connect(self,event):
        self.room_name = 'broadcast'
        self.send({
            'type':'websocket.accept'
        })
        async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name)
        print(f'[{self.channel_name}] - you are connected')
  • Related