ejemplo-de-chat-con-Django/apps/chat/consumers.py

56 lines
1.6 KiB
Python
Raw Permalink Normal View History

2020-11-15 10:52:18 +01:00
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
''' Cliente se conecta '''
# Recoge el nombre de la sala
self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
self.room_group_name = "chat_%s" % self.room_name
# Se une a la sala
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
# Informa al cliente del éxito
await self.accept()
async def disconnect(self, close_code):
''' Cliente se desconecta '''
# Leave room group
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
async def receive(self, text_data):
2020-11-17 20:55:31 +01:00
''' Cliente envía información y nosotros la recibimos '''
2020-11-15 10:52:18 +01:00
text_data_json = json.loads(text_data)
2020-11-17 20:55:31 +01:00
name = text_data_json["name"]
2020-11-15 10:52:18 +01:00
text = text_data_json["text"]
2020-11-17 20:55:31 +01:00
# Enviamos el mensaje a la sala
2020-11-15 10:52:18 +01:00
await self.channel_layer.group_send(
self.room_group_name,
{
"type": "chat_message",
2020-11-17 20:55:31 +01:00
"name": name,
2020-11-17 21:16:53 +01:00
"text": text
2020-11-15 10:52:18 +01:00
},
)
async def chat_message(self, event):
2020-11-17 20:55:31 +01:00
''' Recibimos información de la sala '''
name = event["name"]
2020-11-15 10:52:18 +01:00
text = event["text"]
# Send message to WebSocket
await self.send(
text_data=json.dumps(
{
2020-11-17 20:55:31 +01:00
"type": "chat_message",
"name": name,
2020-11-17 21:16:53 +01:00
"text": text
2020-11-15 10:52:18 +01:00
}
)
)