server+client: fix SSE alternate-event-type handling

I think the server needs to put blank lines after *every* field, not
just the data: fields.
This commit is contained in:
Brian Warner 2015-04-09 11:37:50 -07:00
parent 830ba18fe7
commit 782214813b
2 changed files with 12 additions and 5 deletions

View File

@ -76,16 +76,17 @@ class EventSourceFollower:
# arrived. So unless we set chunk_size=1, we won't hear about lines
# for a long time. I'd prefer that chunk_size behaved like
# read(size), and gave you 1<=x<=size bytes in response.
eventtype = "message"
lines_iter = self.resp.iter_lines(chunk_size=1)
for (fieldname, data) in self._get_fields(lines_iter):
if fieldname == "data":
yield data
yield (eventtype, data)
eventtype = "message"
elif fieldname == "event":
eventtype = data
else:
print("weird fieldname", fieldname, data)
def get_message(self):
return self.iter_events().next()
class Common:
def url(self, verb, msgnum=None):
url = "%s%d/%s/%s" % (self.relay, self.channel_id, self.side, verb)
@ -110,7 +111,10 @@ class Common:
raise Timeout
#time.sleep(self.wait)
f = EventSourceFollower(self.url(verb, msgnum), remaining)
msgs = [json.loads(f.get_message())["message"]]
for (eventtype, data) in f.iter_events():
if eventtype == "message":
msgs = [json.loads(data)["message"]]
break
f.close()
return msgs

View File

@ -30,10 +30,13 @@ class EventsProtocol:
# e.g. if name=foo, then the client web page should do:
# (new EventSource(url)).addEventListener("foo", handlerfunc)
# Note that this basically defaults to "message".
self.request.write("\n")
if id:
self.request.write("id: %s\n" % id.encode("utf-8"))
self.request.write("\n")
if retry:
self.request.write("retry: %d\n" % retry) # milliseconds
self.request.write("\n")
for line in data.splitlines():
self.request.write("data: %s\n" % line.encode("utf-8"))
self.request.write("\n")