demo-HTML-over-WebSockets-i.../apps/back/consumers.py

55 lines
1.5 KiB
Python
Raw Normal View History

2021-03-07 18:15:29 +01:00
import json
from channels.generic.websocket import AsyncWebsocketConsumer
2021-03-08 21:25:34 +01:00
class BlogConsumer(AsyncWebsocketConsumer):
2021-03-07 18:15:29 +01:00
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 = "blog_%s" % self.room_name
# Se une a la sala
2021-03-08 21:25:34 +01:00
self.channel_layer.group_add(self.room_group_name, self.channel_name)
2021-03-07 18:15:29 +01:00
# Informa al cliente del éxito
2021-03-08 21:25:34 +01:00
self.accept()
2021-03-07 18:15:29 +01:00
def disconnect(self, close_code):
''' Cliente se desconecta '''
# Leave room group
2021-03-08 21:25:34 +01:00
self.channel_layer.group_discard(self.room_group_name, self.channel_name)
2021-03-07 18:15:29 +01:00
def receive(self, text_data):
''' Cliente envía información y nosotros la recibimos '''
text_data_json = json.loads(text_data)
name = text_data_json["name"]
text = text_data_json["text"]
# Enviamos el mensaje a la sala
2021-03-08 21:25:34 +01:00
self.channel_layer.group_send(
2021-03-07 18:15:29 +01:00
self.room_group_name,
{
"type": "chat_message",
"name": name,
"text": text
}
)
def chat_message(self, event):
''' Recibimos información de la sala '''
name = event["name"]
text = event["text"]
# Send message to WebSocket
2021-03-08 21:25:34 +01:00
self.send(
2021-03-07 18:15:29 +01:00
text_data=json.dumps(
{
"type": "chat_message",
"name": name,
"text": text
}
)
)