This commit is contained in:
aqu415
2022-02-14 21:46:12 +08:00
parent a30894d2aa
commit 4074afd250
4 changed files with 42 additions and 8 deletions
+31 -7
View File
@@ -1,17 +1,41 @@
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'chat%s' % bytes.decode(self.scope['query_string'])
print(self.room_group_name)
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
pass
# Leave room group
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
def receive(self, text_data):
print('%s' % text_data)
self.send(text_data=json.dumps({
'message': 'message'
}))
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
# chat_message 方法
'type': 'chat_message',
'message': text_data
}
)
# Receive message from room group
def chat_message(self, event):
message = event['message']
# Send message to WebSocket
self.send(text_data=message)