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

谁说胖子不能爱 提交于 2019-12-24 10:35:48

问题


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?


回答1:


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'}


来源:https://stackoverflow.com/questions/11519329/how-to-have-multiple-clients-listen-to-a-server-sent-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!