1 year ago

#65002

test-img

Mueez Khan

How to find which channel sent a particular message in Django channels + Websocket api?

I am implementing a broadcaster using Django channels i.e, i am implementing a group of channels where a message sent from a single consumer instance associated with a channel will be sent to all other instances that have their associated channels registered in that group.

I am using the template as following:

<!-- {% load static %} -->
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Messages</title>
        <!-- <link href="{% static 'hello/styles.css' %}" rel="stylesheet"> -->
    </head>
    <body>
        <textarea name="" id="chat-log" cols="100" rows="20"></textarea><br>
        <input type="text" id="chat-message-input" size="100"><br>
        <input type="button" value="send" id="chat-message-submit">
        <script>
            var ws = new WebSocket('ws://127.0.0.1:8000/ws/sc/')

            ws.onopen = function(){
                console.log('Websocket connection open....', event)
            }
            ws.onmessage = function(event){
                const messageTextDom = document.getElementById('chat-log')
                messageTextDom.value += JSON.parse(event['data']).msg + '\n'
                console.log('Message Recieved From Serever...', event)
            }
            ws.onerror = function(event){
                console.log('Message Error Occured...', event)
            }
            ws.onclose = function(event){
                console.log('Webdsocket connection closed..', event)
            }

            document.getElementById('chat-message-submit').onclick = 
            function(event){
                const messageInputDom = document.getElementById('chat-message-input')
                const message = messageInputDom.value
                ws.send(JSON.stringify({
                    'msg': message
                }))
                messageInputDom.value = ''
            }
        </script>
    </body>
</html>

and have setup the group and message sending utility on the backend as:

from channels.generic.websocket import SyncConsumer
from asgiref.sync import async_to_sync
from channels.exceptions import StopConsumer


class TestConsumer(SyncConsumer):

    def websocket_connect(self, event):
      
       async_to_sync(self.channel_layer.group_add)('programmers', self.channel_name)
       self.send({
           'type': 'websocket.accept'
       })
   
    def websocket_receive(self, event):

        async_to_sync(self.channel_layer.group_send)('programmers', {
           'type': 'chat_message',
           'message': event['text']
       })
        
    def chat_message(self, event):

        self.send({
           'type': 'websocket.send',
           'text': event['message']
       })

    def websocket_disconnect(self, *args, **kwargs):
        async_to_sync(self.channel_layer.group_discard)('programmers', self.channel_name)
        raise StopConsumer()

How can i find which user sent the message and by comparing on the bases of user that sent the message perform some action e.g, in whatsApp in a conversation in user1's view (consumer web instance) his messages gets displayed on the right side with green background, while in user2's view (consumer web instance) his messages gets displayed on the right side with green background.

django

websocket

django-channels

0 Answers

Your Answer

Accepted video resources