python-scripts/scripts/Chat-App/chat/consumers.py
Raj Saha b4e2d6e874
Upload Chat-App
uploaded the required files
2022-10-09 10:52:32 +05:30

31 lines
949 B
Python

import json
from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.roomGroupName = "group_chat_gfg"
await self.channel_layer.group_add(
self.roomGroupName ,
self.channel_name
)
await self.accept()
async def disconnect(self , close_code):
await self.channel_layer.group_discard(
self.roomGroupName ,
self.channel_layer
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json["message"]
username = text_data_json["username"]
await self.channel_layer.group_send(
self.roomGroupName,{
"type" : "sendMessage" ,
"message" : message ,
"username" : username ,
})
async def sendMessage(self , event) :
message = event["message"]
username = event["username"]
await self.send(text_data = json.dumps({"message":message ,"username":username}))