我是Python和Django的新手,
目前,我需要使用通道设置WebSocket服务器。
setting.py
ASGI_APPLICATION = 'myapp.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}
下面是代码Consumer
import json
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
class ZzConsumer(WebsocketConsumer):
def connect(self):
self.room_group_name = 'test'
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
print("DISCONNECED CODE: ",code)
def receive(self, text_data=None, bytes_data=None):
print(" MESSAGE RECEIVED")
data = json.loads(text_data)
message = data['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
"type": 'chat_message',
"message": message
}
)
def chat_message(self, event):
print("EVENT TRIGERED")
# Receive message from room group
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'type': 'chat',
'message': message
}))
和消费者之外:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'test',
{
'type': 'chat_message',
'message': "event_trigered_from_views"
}
)
期望的逻辑是我可以从Consumer类上的receive
中的group_send
接收数据。这样我可以发送消息给客户端。
然而,它不是。
这里有人知道我错过了什么吗?非常感谢任何帮助。
谢谢!
更新:
routing.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/socket-server/', consumers.ZzConsumer.as_asgi())
]
我认为你在chat_message
方法中缺少type
参数。它应该与group_send
中的类型匹配。例如:
def chat_message(self, event, type='chat_message'):
print("EVENT TRIGERED")
匹配:
async_to_sync(channel_layer.group_send)(
'test',
{
'type': 'chat_message',
'message': "event_trigered_from_views"
}
)