利用flask和redis進行推送

服務端代碼:html

from flask import Flask, make_response, render_template
import time, redisredis

app = Flask(__name__)flask

@app.route('/')
def home():
  return render_template('index.html')服務器


@app.route('/sse')
def index():
  r = redis.Redis(host='127.0.0.1')
  p = r.pubsub()
  r.publish('mud','我來啦!')
  p.subscribe('mud')
  for i in p.listen():
    if i['type'] == 'message':
      sse = make_response('data:%s \n\n'% i['data'].decode())
      sse.headers['Content-Type']='text/event-stream'
      return sseapp


if __name__ == '__main__':
  app.run(debug=True,host='0.0.0.0',port=80)debug


頁面代碼:code

<!DOCTYPE html>
<html>
<body>
<h1>得到服務器推送</h1>
<div id="result"></div>server

<script>
if(typeof(EventSource)!=="undefined")
  {
  var source=new EventSource("/sse");
  source.onmessage=function(event)
    {
    document.getElementById("result").innerHTML+=event.data + "<br />";
    };
  }
else
  {
  document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
  }
</script>htm

</body>
</html>ip

相關文章
相關標籤/搜索