2015-10-08 32 views
0

我有一服務器SSE:如下面給出的發送輸出(例如http://www.howopensource.com/2014/12/introduction-to-server-sent-events/)。每個數據部分用兩個新行(\ n \ n)分隔。我想寫一個簡單的python程序來連續顯示SSE輸出。雷丁SSE數據在python

... 

id: 5 
data: Got ID: 5 and the data will be like this. 

id: 6 
data: Got ID: 6 and the data will be like this. 

id: 7 
data: Got ID: 7 and the data will be like this. 

... 

我試過下面的python代碼。

from __future__ import print_function 
import httplib 

conn = httplib.HTTPConnection("localhost") 
conn.request("GET", "/sse.php") 
response = conn.getresponse() 

while True: 
    data = response.read(1) 
    print(data, end='') 

上面的代碼完全適合我。但它會爲每個角色進行迭代。我不知道有什麼方法可以每次迭代打印每個數據部分。

回答

1

可以使用response.fp.readline按行讀入數據線

from __future__ import print_function 
import httplib 
conn = httplib.HTTPConnection("localhost") 
conn.request("GET", "/sse.php") 
response = conn.getresponse() 

while True: 
    data = response.fp.readline() 
    print(data)