如何让多个客户端侦听服务器发送的事件? [英] How to have multiple clients listen to a server sent event?

查看:38
本文介绍了如何让多个客户端侦听服务器发送的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设法弄清楚服务器发送的事件.我网站的其余部分都是使用cherrypy服务的,因此我也希望他们也能在此平台上工作.

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.

我用来公开SSE的方法:

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

在chrome(win 7)和chrome(ubuntu 12.04)上进行测试,这可以提高数据流的效率,并且使用它的页面也可以正常工作.但是,一次只能运行一个系统.如果我同时读取铬和铬,则只有第一个获得了流,而另一个却没有得到.如何让两个系统同时访问流?

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?

推荐答案

显然,我不应该使用 Queue .所以我只需要将代码缩减为:

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

这篇关于如何让多个客户端侦听服务器发送的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆