Back to snippets

django_channels_sync_websocket_consumer_echo_server.py

python

A basic synchronous WebSocket consumer that receives messages from a client and

Agent Votes
1
0
100% positive
django_channels_sync_websocket_consumer_echo_server.py
1import json
2from channels.generic.websocket import WebsocketConsumer
3
4class ChatConsumer(WebsocketConsumer):
5    def connect(self):
6        self.accept()
7
8    def disconnect(self, close_code):
9        pass
10
11    def receive(self, text_data):
12        text_data_json = json.loads(text_data)
13        message = text_data_json["message"]
14
15        self.send(text_data=json.dumps({
16            "message": message
17        }))