Sending Message back to Client using Django Channels (and REST Framework)

I have just started to use Django channels with djangochannelrestframework and playing around with it. Right now I am trying to let the server side send me back messages to my browser (Not to group). Here is my code:

consumer.py

class SimulationConsumer(ObserverModelInstanceMixin, GenericAsyncAPIConsumer):

    async def connect(self):
        await self.accept()
        print("Connected to simulation core. ")

    @action()
    async def test(self, **kwargs):
        message = ("Success")
        print(message)
        await self.send(message)

When I tested the code with browser with the following script, I don’t see any responses back.


Which I am expecting to see “Success” from the second command but it becomes undefined. Just wanted to know what I am missing (and where in the documentations that can shed me a light)?

Update: Don’t worry about the endpoint URL, I copied the tutorial just to try out. At the serverside I can see "Connected to simulation core. " and “Success” printed but not the on my browser.

Welcome @lt-shy-john !

You need JavaScript code in the browser to receive the websocket response(s) and do something with it.

See Writing WebSocket client applications - Web APIs | MDN as one source of more detailed information.

Hi Ken,

Thanks for the reply. I will have a look at your article.

John

Thanks Ken for the guide, I found that I just need to add the following in my script:

const ws = new WebSocket('ws://localhost:8000/ws/chat/room/');
ws.onmessage = (event) => {
  console.log(event.data);
};

After that I can test the code with the test event as usual:

ws.send(JSON.stringify({"pk": 1, "action": "test", "request_id": 1}));