问题
I have a SSE server(eg: http://www.howopensource.com/2014/12/introduction-to-server-sent-events/) that sends output as given below. Each data section is separated with two new lines(\n\n). I want to write down a simple python program to display the SSE output continuously.
...
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.
...
I tried following python code.
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='')
The above code works perfectly to me. But it do iteration for each character. I wonder there is any way to print each data-section per iteration.
回答1:
you can use response.fp.readline to read data line by line
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)
来源:https://stackoverflow.com/questions/33022039/reading-sse-data-in-python