3

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

我已经研究过使用彗星/长轮询,但在我的一生中,我无法让浏览器在接收到数据时呈现数据。

为了原型这个机制,我写了以下内容:

时钟.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()

索引.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直接转储到一个 div.readyState == 4.status == 200

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

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

4

2 回答 2

0

那么使用“HTTP 流”呢?我已成功使用它将日志从服务器“流式传输”到“侦听”浏览器。这是一个使用扭曲和一点 js 的简单实现:http: //codelab.ferrarihaines.com/archives/161

于 2012-08-29T16:19:08.720 回答
0

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

于 2011-05-07T04:16:17.467 回答