2011-05-07 89 views
3

我正在使用Twisted編寫Web服務器。此服務器執行的任務之一需要很長時間(〜5分鐘)。我希望能夠有效地通知客戶此任務已完成。扭曲:服務器端進程完成時通知客戶端

我已經研究過使用Comet/long polling,但是對於我的生活,我無法讓瀏覽器在接收到數據時呈現數據。

爲原型這個機制,我寫了下面:

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直接轉儲到div中,只要.readyState == 4.status == 200

問題是:div永遠不會被覆蓋,警報也不會被調用。

我一直在閱讀有關使用multipart/x-mixed-replace,但我不確定如何使用它。任何指向教程或文件的扭曲實現這種事情將不勝感激。

回答

0

考慮在循環中添加一個p.finish(),以便請求實際完成。目前的實施將永遠掛起。

0

那麼使用「HTTP流式傳輸」呢?我已經成功地使用它將來自服務器的日誌「流式傳輸」到「監聽」瀏覽器。這是一個簡單的實現,使用扭曲和一點js:http://codelab.ferrarihaines.com/archives/161

+0

這裏沒有公佈這裏的作者。 – 2012-10-02 12:40:25