【发布时间】:2011-08-20 14:34:39
【问题描述】:
我正在使用 Twisted 编写一个 Web 服务器。此服务器执行的任务之一需要很长时间(约 5 分钟)。我希望能够有效地通知客户此任务已完成。
我已经研究过使用 Comet/长轮询,但在我的一生中,我无法让浏览器在接收到数据时呈现数据。
为了对这种机制进行原型设计,我编写了以下代码:
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 到适当的资源,并在 .readyState == 4 和 .status == 200 时将 responseText 直接转储到一个 div 中。
问题是:div 永远不会被覆盖,并且警报永远不会被调用。
我一直在阅读有关使用 multipart/x-mixed-replace 的信息,但我不确定如何使用它。任何关于在 twisted 中实现此类事情的教程或文档的指针将不胜感激。
【问题讨论】:
标签: twisted comet long-polling notify multipart-mixed-replace