我在consumers.py中有以下代碼
from channels.consumer import SyncConsumer
from asgiref.sync import async_to_sync
class EchoConsumer(SyncConsumer):
def websocket_connect(self,event):
self.room_name = 'broadcast'
self.send({
'type':'websocket.accept'
})
async_to_sync(self.channel_layer.group_add(self.room_name, self.channel_name))
print(f'[{self.channel_name}] - you are connected')
def websocket_receive(self,event):
print(f'[{self.channel_name}] - Recieved message - {event["text"]}')
async_to_sync(self.channel_layer.group_send)(
self.room_name,
{
'type': 'websocket.message',
'text': event.get('text')
}
)
def websocket_message(self,event):
print(f'[{self.channel_name}] - message Sent - {event["text"]}')
self.send({
'type':'websocket.send',
'text':event.get('text')
})
def websocket_disconnect(self,event):
print(f'[{self.channel_name}] - disconnected')
print('connection is disconnected')
async_to_sync(self.channel_layer.group_discard(self.room_name, self.channel_name))
我想在收到訊息時呼叫訊息函式,所以在 websocket_recieve 函式中我添加了'type': 'websocket.message',但我不知道為什么沒有呼叫 websocket_message 函式?
我是 django 頻道的新手。訊息從任何連接成功接收,但沒有發送到任何連接。
任何幫助將不勝感激。
uj5u.com熱心網友回復:
將 websocket_connect 函式更改為此
def websocket_connect(self,event):
self.room_name = 'broadcast'
self.send({
'type':'websocket.accept'
})
async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name)
print(f'[{self.channel_name}] - you are connected')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/337561.html
