1

我正在一個簡單的網絡應用程序,這是完成與角度和cherrypy(原型現在)。我正在上傳兩個文件,然後使用子進程(popen)在cherrypy內調用外部python程序來處理它們。我能夠做到這一點。我想要實現的是外部程序(我通過popen捕捉到)的輸出傳遞給客戶端。我的問題是,我正嘗試在cherrypy上設置服務器發送的事件,但沒有成功。如何設置cherrypy服務器發送事件

這裏是我的CherryPy的方法,我(從網絡的例子之一)暴露:

@cherrypy.expose 
def getUpdate(self): 
    #Set the expected headers... 
    cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8" 
    def content(): 
     yield "Hello," 
     yield "world" 
    return content() 

這裏是JavaScript客戶端代碼(我已經啓用CORS和工作):

var sseEvent = new EventSource('http://localhost:8090/getUpdate'); 
sseEvent.onmessage = function (event) { 
    console.log(event); 
}; 
sseEvent.onopen = function (event) { 
    //console.log("I have started..."); 
}; 

我已經看過這個question和這個blog。但是,從服務器端調用函數時,EventSource對象上的onmessage事件不會觸發。我的理解是,你可以從服務器端調用這個函數,它會從瀏覽器捕獲事件。我錯了,或者設置錯了?

回答

2

所以我想通過SSE,我需要以特定的格式發送數據。即

  • 數據: 「富\ n \ n」

或JSON

  • data: "{\n data: "msg" : "foo", \n data: "id" : "boo", \n data: "}\n\n

我想要的是一個重試的格式,以保持輪詢什麼服務器在n秒後。所以CherryPy的功能現在是:

@cherrypy.expose 
def getUpdate(self, _=None): 
    cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8" 
    if _: 
     data = 'retry: 200\ndata: ' + str(self.prog_output) + '\n\n' 
     return data 
    else: 
     def content(): 
      data = 'retry: 200\ndata: ' + str(self.prog_output) + '\n\n' 
      return data 
     return content() 

getUpdate._cp_config = {'response.stream': True, 'tools.encode.encoding':'utf-8'} 

,現在在哪裏發送的消息是一個

'重試:N微秒'

這將發送的數據每n微秒。現在EventSource onmessage事件正在被觸發,我很高興地從服務器發送的程序中讀取輸出。 :)

對於SSE的一個很好的閱讀(如在許多帖子中提到的):here