Skip to content Skip to sidebar Skip to footer

Send Message Using Django Channels From Outside Consumer Class

I am building an online game, which uses Django channels 2.1.5 for websockets. I am able to build the connection between the client and the server, and also able to send data betwe

Solution 1:

Firstly you need your consumer instance to subscribe to a group.

from asgiref.sync import async_to_sync

classGameConsumer(WebsocketConsumer):
    defconnect(self):
        self.accept()
        self.render()
        async_to_sync(self.add_group)('render_updates_group') 
        controller.startTurn()
...

Then if you are outside of your consumer you will need to send a message to that group so that all the consumers that have registered onto the group get the message.

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

defsendDeployments(owner, armies):
    type = "renderDeployments"
    message = owner + " has " + str(armies) + " to deploy"
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'render_updates_group',
        {'type': 'render', 'message': message}
    )

However, you also need to remember to remove your consumer from the group when it disconnects.

classGameConsumer(WebsocketConsumer):
    ....

    defdisconnect(self, close_code):
         async_to_sync(self.group_name)('render_updates_group')

If you want to limit which open connections get this render message you need to build your group name accordingly.

eg if you are thinking about some online game then maybe you include a MATCH-ID in the group name that is shared by all connections for the same match.

A good reference for this is the channels Layers documentation but do remember when running this in production you will need a messaging layer (normally Redis) set up.

Solution 2:

First make a little change for your Consumer like

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json

classEventConsumer(WebsocketConsumer):
    defconnect(self):
        # self.room_name = self.scope['url_route']['kwargs']['room_name']# self.room_group_name = 'chat_%s' % self.room_name
        self.room_name = 'event'
        self.room_group_name = self.room_name+"_sharif"
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        print(self.room_group_name)
        self.accept()
        print("#######CONNECTED############")

    defdisconnect(self, code):
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
        print("DISCONNECED CODE: ",code)

    defreceive(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": 'send_message_to_frontend',
                "message": message
            }
        )
    defsend_message_to_frontend(self,event):
        print("EVENT TRIGERED")
        # Receive message from room group
        message = event['message']
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

then call the function outside/anywhere from your app like

defevent_triger():
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'event_sharif',
        {
            'type': 'send_message_to_frontend',
            'message': "event_trigered_from_views"
        }
    ) 
# here 'event_sharif' is your room_group_name as i defined before in consumer# 'type' is like a command, for which method you wants to trigger in your consumer

Solution 3:

The correct code for the disconnect function (using channels 2.3.0) would be:

classGameConsumer(WebsocketConsumer):
    ....

    defdisconnect(self, close_code):
        self.channel_layer.group_discard(self.channel_name, 'render_updates_group')

Post a Comment for "Send Message Using Django Channels From Outside Consumer Class"