Search code examples
pythoncherrypyserver-sent-events

How to have multiple clients listen to a server sent event?


I am trying to get my head around server sent events. The rest of my site is served using cherrypy, so I want to get them working on this platform too.

The method I'm using to expose the SSE:

@cherrypy.expose
def interlocked(self, _=None):
    cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8"
    if _:
        data = 'retry: 400\n'
        while not self.interlockUpdateQueue.empty():
            update = self.interlockUpdateQueue.get(False)
            data += 'data: ' + str(update) + '\n\n'
        return data
    else:
        def content():
            while not self.interlockUpdateQueue.empty():
                update = self.interlockUpdateQueue.get(True, 400)
                data = 'retry: 400\ndata: ' + str(update) + '\n\n'
                yield data
        return content()
interlocked._cp_config = {'response.stream': True, 'tools.encode.encoding':'utf-8'}

Testing on chrome (win 7) and chromium (ubuntu 12.04) this serves the stream up and the page using it works fine. However it only works one system at a time. If I have both chrome and chromium reading the stream, only the first one gets the stream, the other one gets nothing. How do I give both systems access to the stream simultaneously?


Solution

  • Apparently I shouldn't be using a Queue. So I just needed to cut down my code to:

    @cherrypy.expose
    def interlocked(self, _=None):
        cherrypy.response.headers["Content-Type"] = "text/event-stream;charset=utf-8"
        if _:
            data = 'retry: 400\ndata: ' + str(self.isInterlocked) + '\n\n'
            return data
        else:
            def content():
                data = 'retry: 400\ndata: ' + str(self.isInterlocked) + '\n\n'
                return data
            return content()
    interlocked._cp_config = {'response.stream': True, 'tools.encode.encoding':'utf-8'}