Django 循环中的JsonWebsocketConsumer类self.send()一次发送所有迭代消息
当我在循环中使用self.send(content)时,所有消息都会一次发送,而不是一条我的消息 if条件od connecting中的第一个self.send()被完美执行 但是,客户机会在大约60秒的延迟后立即接收所有循环self.send()消息。如何一次做一个Django 循环中的JsonWebsocketConsumer类self.send()一次发送所有迭代消息,django,websocket,django-channels,Django,Websocket,Django Channels,当我在循环中使用self.send(content)时,所有消息都会一次发送,而不是一条我的消息 if条件od connecting中的第一个self.send()被完美执行 但是,客户机会在大约60秒的延迟后立即接收所有循环self.send()消息。如何一次做一个 consumer.py from channels.generic.websockets import JsonWebsocketConsumer class MyConsumer(JsonWebsocketConsumer):
consumer.py
from channels.generic.websockets import JsonWebsocketConsumer
class MyConsumer(JsonWebsocketConsumer):
# Set to True if you want it, else leave it out
strict_ordering = False
def connect(self, message, **kwargs):
super(MyConsumer,self).connect(message)
pass
def receive(self, content, **kwargs):
if content['status'] == "connecting":
content['status'] = "connected"
self.send(content)
elif content['status'] == "data":
for p in range(5):
content={
'status': 'sending',
'polygon': p
}
self.send(content)
time.sleep(15)
self.close()
def disconnect(self, message, **kwargs):
pass
clientside.js
socket = new WebSocket("ws://" + location.host + "/mahaplans/");
socket.onopen = function () {
var msg = {
status: "connecting"
};
socket.send(JSON.stringify(msg))
}
socket.onmessage = function (e) {
let status=JSON.parse(e.data)
if (status["status"]=="connected") {
var imageData={
#someddata
}
socket.send(JSON.stringify(imageData))
}
if (status["status"]=="sending") {
console.log(status["polygon"])
}
}
socket.onclose = function (event) {
console.log("bye bye")
}
if (socket.readyState == WebSocket.OPEN) socket.onopen();
我建议使用
AsyncWebsocketConsumer
然后您可以Wait
发送和等待异步。
Wait asyncio.sleep(1)。在同步使用者中,使用者可能无法处理您的
send`事件,直到receive
方法完成。@MatthausWoolard我使用的是Django Channel 1.8,因此我无法使用AsyncWebsocketConsumer。这个问题还有其他解决方案吗?v2之前的通道有一个非常不同的运行时模型,我恐怕不太熟悉。是否有什么东西阻止您升级到v2?是的。由于某些原因,我无法升级到v2。感谢您告诉我原因,即接收功能完成。我通过改变逻辑并使用if而不是for来解决这个问题,并为每次迭代发送一条消息,以便每次都完成receive函数。