zoukankan      html  css  js  c++  java
  • 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="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()
  • 相关阅读:
    大型网站应用中MySQL的架构演变史
    SRM 585 DIV2
    TC 配置插件
    Java中含有静态成员的的初始化顺序
    java 23种设计模式,一般情况下,常用的有哪些? 转载
    Java中的正则表达式
    C++ 中的关于输出的设置于
    C++实现可变参数列表
    Java中的组合与聚合
    pku 2284 That Nice Euler Circuit
  • 原文地址:https://www.cnblogs.com/KnowledgeSky/p/9426710.html
Copyright © 2011-2022 走看看