gpt4 book ai didi

Twisted:在服务器端进程完成时通知客户端

转载 作者:行者123 更新时间:2023-12-01 13:29:42 25 4
gpt4 key购买 nike

我正在使用 Twisted 编写 Web 服务器。该服务器执行的其中一项任务需要很长时间(约 5 分钟)。我希望能够有效地通知客户此任务已完成。

我研究过使用 Comet/long polling,但我无法让浏览器在收到数据时呈现数据。

为了构建这个机制的原型(prototype),我写了以下内容:

时钟.py

from twisted.internet import reactor, task
from twisted.web.static import File
from twisted.web.server import Site
from twisted.web import server
from twisted.web.resource import Resource
import time

class Clock(Resource):
def __init__(self):
self.presence=[]
loopingCall = task.LoopingCall(self.__print_time)
loopingCall.start(1, False)
Resource.__init__(self)

def render_GET(self, request):
print "request from",request.getClientIP()
request.write(time.ctime())
self.presence.append(request)
return server.NOT_DONE_YET

def __print_time(self):
print "tick"
for p in self.presence:
print "pushing data to",p.getClientIP()
p.write(time.ctime())

root = Resource()
clock = ClockPage()
index = File("index.html")
root.putChild("index.html",index)
root.putChild("clock",clock)
factory = Site(root)
reactor.listenTCP(8080, factory)
reactor.run()

index.html

<html>
<head>
</head>
<body>
<div id="data">Hello</div>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(xhttp.readyState == 4 && xhttp.status == 200){
alert(xhttp.responseText);
document.getElementById("data").innerHTML=xhttp.responseText;
}
};
xhttp.open("GET","clock",true);
xhttp.send(null);
</script>
</body>
</html>

我一直在服务器端做的是每秒调用 request.write

在客户端,我所做的就是打开一个 XMLHTTPRequest 到适当的资源,并在 .readyState == 4 时将 responseText 直接转储到 div 中>.status == 200.

问题是:div 永远不会被覆盖,也永远不会调用警报。

我一直在阅读有关使用 multipart/x-mixed-replace 的信息,但我不太确定如何使用它。非常感谢任何关于在扭曲中实现此类事情的教程或文档的指针。

最佳答案

考虑将 p.finish() 添加到您的循环中,以便请求真正完成。当前的实现将永远挂起。

关于Twisted:在服务器端进程完成时通知客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5918916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com