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

时间:2011-05-07 03:25:18

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

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

我已经研究过使用Comet / long轮询,但对于我的生活,我无法让浏览器在收到数据时呈现数据。

为了对这种机制进行原型化,我写了以下内容:

clock.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到相应的资源,并在responseText.readyState == 4时将.status == 200直接转储到div中。

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

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

2 个答案:

答案 0 :(得分:0)

考虑在循环中添加p.finish(),以便请求实际完成。目前的实施将永远悬而未决。

答案 1 :(得分:0)

如何使用&#34; HTTP流媒体&#34;代替?我已成功使用它来&#34; stream&#34;记录从服务器到&#34; listen&#34;浏览器。这是一个使用twisted和js的简单实现:http://codelab.ferrarihaines.com/archives/161