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

标签 twisted comet long-polling notify multipart-mixed-replace

我正在使用 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/

相关文章:

python - 扭曲的服务器信息

tomcat7 - Tomcat 错误 : java. lang.IllegalStateException:调用 [asyncPostProcess()] 对具有异步状态 [STARTED] 的请求无效

c# - 寻找 cometd 式服务器或客户端

Python:SocketServer 意外关闭 TCP 连接

python - Scrapy:蜘蛛中间件中的异步数据库请求?

python - sendLine 中的扭曲类型错误

php - 实现 Comet 服务器端后端的最简单方法是什么?

comet - 可重放 cometd 风格应用程序(Google Wave、Etherpad)的高效存储/检索方法

comet - 异步servlet长轮询和bayeux协议(protocol)( cometd )之间的区别

ajax,长轮询和管理两分钟重试