【问题标题】:Twisted: notify client when server-side process completesTwisted:当服务器端进程完成时通知客户端
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这里没有披露作者身份。
      猜你喜欢
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      相关资源
      最近更新 更多