码迷,mamicode.com
首页 > 编程语言 > 详细

flask python geventwebsocket实现websocket

时间:2018-08-05 18:59:13      阅读:1022      评论:0      收藏:0      [点我收藏+]

标签:后端   rms   out   dump   erro   rip   lis   ack   text   

前端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()

 

flask python geventwebsocket实现websocket

标签:后端   rms   out   dump   erro   rip   lis   ack   text   

原文地址:https://www.cnblogs.com/KnowledgeSky/p/9426710.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!