<p>看看<a href="http://dev.w3.org/html5/eventsource/">Server-Sent Events</a>。服务器发送的事件是
浏览器API,允许您保持打开服务器的套接字,订阅
更新流。有关更多信息,请阅读Alex MacCaw(作者
(魔术师)在<a href="http://blog.alexmaccaw.com/killing-a-library">why he kills juggernaut</a>上的帖子以及为什么
在manny情况下,服务器发送的事件比
韦伯塞特。</p>
<p>协议很简单。只需将mimetype<code>text/event-stream</code>添加到
回应。浏览器将保持连接打开并监听更新。事件
从服务器发送的是以<code>data:</code>开头的一行文本和以下换行符。</p>
<pre><code>data: this is a simple message
<blank line>
</code></pre>
<p>如果您想交换结构化数据,只需将数据转储为json并通过网络发送json即可。</p>
<p>一个优点是你可以在烧瓶中使用SSE而不需要额外的
服务器。github上有一个简单的<a href="https://github.com/jkbr/chat">chat application example</a>
使用redis作为发布/订阅后端。</p>
<pre><code>def event_stream():
pubsub = red.pubsub()
pubsub.subscribe('chat')
for message in pubsub.listen():
print message
yield 'data: %s\n\n' % message['data']
@app.route('/post', methods=['POST'])
def post():
message = flask.request.form['message']
user = flask.session.get('user', 'anonymous')
now = datetime.datetime.now().replace(microsecond=0).time()
red.publish('chat', u'[%s] %s: %s' % (now.isoformat(), user, message))
@app.route('/stream')
def stream():
return flask.Response(event_stream(),
mimetype="text/event-stream")
</code></pre>
<p>你不需要用枪来操作
应用程序示例。运行应用程序时请确保使用线程,因为
否则,SSE连接将阻止您的开发服务器:</p>
<pre><code>if __name__ == '__main__':
app.debug = True
app.run(threaded=True)
</code></pre>
<p>在客户端,您只需要一个Javascript处理函数,当一个新的
从服务器推送消息。</p>
<pre><code>var source = new EventSource('/stream');
source.onmessage = function (event) {
alert(event.data);
};
</code></pre>
<p>服务器发送的事件是最近的Firefox、Chrome和Safari浏览器发送的<a href="http://caniuse.com/#feat=eventsource">supported</a>。
Internet Explorer尚不支持服务器发送的事件,但在
版本10。有两个推荐的polyfill来支持旧的浏览器</p>
<ul>
<li><a href="https://github.com/remy/polyfills/blob/master/EventSource.js">EventSource.js</a></li>
<li><a href="https://github.com/rwldrn/jquery.eventsource">jquery.eventsource</a></li>
</ul>