2020-09-18 16:11:19 +00:00
|
|
|
import json
|
|
|
|
from asgiref.sync import async_to_sync
|
|
|
|
from channels.generic.websocket import AsyncWebsocketConsumer
|
2020-09-03 02:56:28 +00:00
|
|
|
|
|
|
|
|
2020-09-18 16:11:19 +00:00
|
|
|
class ChatConsumer(AsyncWebsocketConsumer):
|
2020-09-03 02:56:28 +00:00
|
|
|
async def connect(self):
|
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-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
|
|
|
|
async def receive(self, text_data):
|
|
|
|
text_data_json = json.loads(text_data)
|
2020-09-20 11:14:54 +00:00
|
|
|
print('receive from websock', text_data_json)
|
|
|
|
# message = text_data_json['message']
|
|
|
|
|
|
|
|
# # Send message to room group
|
|
|
|
# await self.channel_layer.group_send(
|
|
|
|
# self.room_group_name,
|
|
|
|
# {
|
|
|
|
# 'type': 'chat_message',
|
|
|
|
# 'message': 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-18 16:11:19 +00:00
|
|
|
message = event['message']
|
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-20 11:14:54 +00:00
|
|
|
# await self.send(text_data=json.dumps({
|
|
|
|
# 'message': message
|
|
|
|
# }))
|