[英]Django channels consumer
对于 django 频道,我有这样的消费者文件:
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
import json
class chatConsumer(WebsocketConsumer):
def connect(self):
async_to_sync(self.channel_layer.group_add)(
'my_socket',
self.channel_name
)
self.accept()
def receive(self, text_data):
async_to_sync(self.channel_layer.group_send)(
'my_socket',
{
'type': 'chat_message',
'data': text_data
}
)
def chat_message(self, event):
json_data = json.loads(event['data']) # get received data as json
respons_test = json.dumps(json_data) # make response text
print("chat_message") # Sometimes this is printed few times
self.send(text_data=respons_test)
似乎chat_message
方法有时会运行几次。 我不确定这到底是如何工作的,但是当我打印到chat_message
时,有时会打印一次,有时会打印不止一次。 (我不改变客户端/浏览器的数量,而且在前端,接收者正确地获取消息,只有一次)。
问题: chat_message
正常运行几次? 还是我的代码有问题?
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 = 'my_socket'
# 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):
# 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):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Receive message from room group
def chat_message(self, event):
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message
}))
使用上面的代码。
它将打印与连接到组my_socket
的客户端一样多的次数。 该组的每个成员都会将消息发送到其频道中的chat_message
处理程序。 检查您的浏览器客户端或打印连接方法以查看有多少客户端连接到该组。 它应该在chat_message
处理程序中打印相同数量的消息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.