flask python geventwebsocket实现websocket
前端js逻辑:
<html> <head></head> <body> <script type="text/javascript" src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> var sock = null; var wsuri = "ws://host:port/openapi/bigevent"; window.onload = function() { console.log("onload"); sock = new WebSocket(wsuri); sock.onopen = function() { console.log("connected to " + wsuri); } sock.onclose = function(e) { console.log("connection closed (" + e.code + ")"); } sock.onerror = function(e) { console.log("connection errored"); } sock.onmessage = function(e) { $("#message").append('<p>' + e.data + '</p>') console.log(JSON.parse(e.data)); }} </script> <h1>WebSocket Echo Test</h1> <div id="message" style="width:600px;height:300px;"></div> </body> </html>
后端逻辑
app.add_url_rule('/openapi/bigevent', view_func=big_event)
# route_url: '/openapi/bigevent' def big_event(): obj = { 'recordsTotal': 0, 'records': [], 'errmsg': "", 'errno': 0, } if request.environ.get('wsgi.websocket'): ws = request.environ['wsgi.websocket'] if ws is None: abort(404) else: x = 0 while True: if not ws.closed: db = mongo.cx[Config.ALFRED_MONGO_DBNAME] filter = {"$and": [{"ts": {"$gt": "1532535132"}}, {"ts": {"$lte": "1532585532"}}]} docs = db.big_event.find(filter, {"_id": 0}) big_event_list = list() for doc in docs: big_event = dict() big_event_list.append(big_event) obj['records'] = big_event_list obj['recordsTotal'] = len(big_event_list) ws.send(json.dumps(obj)) sleep(Config.BIGEVENT_PUSH_CYCLE) else: break
# -*- coding: utf-8 -* from gevent.pywsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler from poseidon.app import create_app from poseidon.settings import Config app = Flask(__name__) if __name__=='__main__': # app.run('0.0.0.0',port=8081) http_server = WSGIServer(('', 8081), app, handler_class=WebSocketHandler) http_server.serve_forever()