Django-guide

Django channels and web sockets

Ahmed Yasin
1 min readNov 1, 2021

We’re using Django channels at server side and react.js at client. We’re going to setup very basic configuration of web sockets for full stack project.

django channels

Server-side:

Python (Django-channels)

import jsonfrom channels.generic.websocket import WebsocketConsumerclass ProjectConsumer(WebsocketConsumer):    def connect(self):        print("connected server")        self.accept()    def disconnect(self, close_code):        print("disconnected server")        pass    def receive(self, text_data):        print("text object from frontend",text_data)        text_data_json = json.loads(text_data)        message = text_data_json['message']        message = text_data        print("message",message)        self.send(text_data=json.dumps({        'message': message         }))

Client-side:

JavaScript (React js)

export const WebSocketTest = () => {var ws = new WebSocket("ws://localhost:8000/ws/projects/");ws.onopen = function() {// Web Socket is connected, send data using send()const msg = JSON.stringify({"firstName": "Jane","lastName": "Doe",})ws.send(msg);alert("Message is sent...");};ws.onmessage = function (evt) {const data = JSON.parse(evt.data);console.log("received_msg",data["message"])alert("Message is received...");};ws.onclose = function() {// websocket is closed.alert("Connection is closed...");};}

Thank You.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ahmed Yasin
Ahmed Yasin

Written by Ahmed Yasin

Youtuber / Content Writer / C++ /Learning Java/ https://www.youtube.com/channel/UC-gDcN99rYbeyH1oKsoPM3A Instagram : belongs_to_mars

No responses yet

Write a response