47 lines
1.3 KiB
Python
47 lines
1.3 KiB
Python
import json
|
|
from asgiref.sync import async_to_sync
|
|
from channels.generic.websocket import AsyncJsonWebsocketConsumer
|
|
|
|
|
|
class ChatConsumer(AsyncJsonWebsocketConsumer):
|
|
async def connect(self):
|
|
print('connect')
|
|
self.room_name = self.scope['url_route']['kwargs']['room_name']
|
|
self.room_group_name = self.room_name
|
|
|
|
# Join room group
|
|
await self.channel_layer.group_add(
|
|
self.room_group_name,
|
|
self.channel_name
|
|
)
|
|
print(self.room_name, 'connected')
|
|
await self.accept()
|
|
|
|
async def disconnect(self, close_code):
|
|
# Leave room group
|
|
await self.channel_layer.group_discard(
|
|
self.room_group_name,
|
|
self.channel_name
|
|
)
|
|
|
|
# Receive message from WebSocket
|
|
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']
|
|
}
|
|
)
|
|
|
|
# Receive message from room group
|
|
async def chat_message(self, event):
|
|
print('receive from room group', event)
|
|
# Send message to WebSocket
|
|
await self.send_json({
|
|
'message': event['message']
|
|
})
|