newmediamonitoring/polls/consumers.py

47 lines
1.3 KiB
Python
Raw Normal View History

2020-09-18 16:11:19 +00:00
import json
from asgiref.sync import async_to_sync
2020-09-22 07:39:33 +00:00
from channels.generic.websocket import AsyncJsonWebsocketConsumer
2020-09-03 02:56:28 +00:00
2020-09-22 07:39:33 +00:00
class ChatConsumer(AsyncJsonWebsocketConsumer):
2020-09-03 02:56:28 +00:00
async def connect(self):
2020-09-22 07:39:33 +00:00
print('connect')
2020-09-18 16:11:19 +00:00
self.room_name = self.scope['url_route']['kwargs']['room_name']
2020-09-20 11:14:54 +00:00
self.room_group_name = self.room_name
2020-09-03 02:56:28 +00:00
2020-09-18 16:11:19 +00:00
# Join room group
2020-09-03 02:56:28 +00:00
await self.channel_layer.group_add(
2020-09-18 16:11:19 +00:00
self.room_group_name,
self.channel_name
2020-09-03 02:56:28 +00:00
)
2020-09-26 01:47:24 +00:00
print(self.room_name, 'connected')
2020-09-18 16:11:19 +00:00
await self.accept()
async def disconnect(self, close_code):
# Leave room group
2020-09-03 02:56:28 +00:00
await self.channel_layer.group_discard(
2020-09-18 16:11:19 +00:00
self.room_group_name,
self.channel_name
2020-09-03 02:56:28 +00:00
)
2020-09-18 16:11:19 +00:00
# Receive message from WebSocket
2020-09-22 07:39:33 +00:00
async def receive_json(self, content):
print('receive from websock', content)
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': content['message']
}
)
2020-09-03 02:56:28 +00:00
2020-09-18 16:11:19 +00:00
# Receive message from room group
2020-09-03 02:56:28 +00:00
async def chat_message(self, event):
2020-09-20 11:14:54 +00:00
print('receive from room group', event)
2020-09-18 16:11:19 +00:00
# Send message to WebSocket
2020-09-22 07:39:33 +00:00
await self.send_json({
'message': event['message']
})