我有一个 Django Channels 消费者类。 WebSocket 连接建立没有任何问题,并且初始消息也已加载。但是,当我尝试发送消息时,它不会触发 async_to_sync 和 chat_message 方法。我已经尝试过多次。 chat_message 函数内的 print 语句不起作用,尽管我尝试捕获异常,但也没有错误。
我已经通过shell检查了通道层和Redis,它们工作正常。后端创建新消息,并收到通知,但没有消息发送到客户端。
class ChatConsumer(WebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user = None
self.room_group_name = None
self.room_code = None
def connect(self):
self.room_code = self.scope['url_route']['kwargs']['room_code']
self.room_group_name = f'chat_{self.room_code}'
self.room = get_object_or_404(ChatRoom, room_code=self.room_code)
try:
try:
self.user = self.scope['user']
except Exception as e:
self.user = None
if self.user == None:
self.close()
return
# Join room group
self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
self.accept()
self.load_initial_messages()
except Exception as e:
print(str(e))
self.close()
def disconnect(self, code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
def receive(self, text_data=None):
text_data_json = json.loads(text_data)
message = text_data_json['message']
msg = Message.objects.create(room=self.room, user=self.user.username, message=message,)
message_data = {
'roomCode': self.room_code,
'user': msg.user,
'message': msg.message,
}
try:
async_to_sync(self.channel_layer.group_send)(
self.room_group_name, {"type": "chat.message", 'message': message_data}
)
print("Message sent to group") # this is getting printed
except Exception as e:
print(f"Error in group_send: {str(e)}")
self.send_notifications(message=message)
def chat_message(self, event):
message = event['message']
print(message) # not getting printed
self.send(text_data=json.dumps({
'roomCode': message['roomCode'],
'user': message['user'],
'message: message['message']
}))
有人可以帮忙解决这个问题吗?
我已经通过shell检查了通道层和Redis,它们工作正常。后端创建新消息,并收到通知,但没有消息发送到客户端。
其实你的最后一行少了一个引号
chat_message功能。
您的代码:
def chat_message(self, event):
message = event['message']
print(message) # not getting printed
self.send(text_data=json.dumps({
'roomCode': message['roomCode'],
'user': message['user'],
'message: message['message'] #here is typo
}))
正确代码:
def chat_message(self, event):
message = event['message']
print(message) # not getting printed
self.send(text_data=json.dumps({
'roomCode': message['roomCode'],
'user': message['user'],
'message': message['message'] #typo removed
}))