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

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

时间: 2024-10-05 07:17:30

flask python geventwebsocket实现websocket的相关文章

测试Flask+PYTHON的WEB框架

参数URL: http://blog.csdn.net/qwiwuqo/article/details/8970621 安装flask之前,你必须要先安装python和easy_install. 安装 virtualenv,这个主要是用来做解释器环境隔离的,避免同一机器上的多个python或者多个python的库依赖. 然后cd到myvir目录的Scripts下输入activate.bat,就进入了虚拟环境了,然后输入easy_install Flask. 测试Flask+PYTHON的WEB框

flask(python)

flask(python) by 伍雪颖 安装flask: $ easy_install flask hello.py: from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello world" if __name__ == "__main__": app.run() 运行: ?  flask git:(master) ? python hello.

python实现的websocket总结 —— wspy

之前曾有php版的websocket封装包,见Websocket--php实战,最近使用python做一些功能,需要用到对websocket的操作,因此,参照之前的实现,实现了这个python版本.源码见https://github.com/OshynSong/wspy. 整体实现起来,需要在建立socket监听端口,这需要用到socket标准库模块:之后,需要对对网络字节流进行操作,这个方面python有struct标准库模块,这个非常好用:另外涉及到加密解密操作,还有hashlib模块和sh

Flask --- Python的另一个轻量级Web框架

Flask是Python中的另一个轻量级Web框架, 在github上有接近15000的star. github地址为Flask 其用法跟Bottle非常类似, 有兴趣可以参考Bottle-Python的轻量级http server. # -*- coding: utf-8 -*- #!/usr/bin/python from flask import Flask, jsonify app = Flask(__name__) @app.route('/') def index(): return

python简单实现websocket

协议选择的是新的Hybi-10,参考文章如下: http://www.cnblogs.com/zhuweisky/p/3930780.html http://blog.mycolorway.com/2011/11/22/a-minimal-python-websocket-server/ http://blog.csdn.net/icechenbing/article/details/7407588 python代码如下: #-*- coding:utf8 -*- import threadin

CentOS7.2安装配置nginx+flask+python+uwsgi运行环境

操作系统:CentOS 7.2 Nginx安装请参考centos7.2安装nginx这个文章 1. 安装python3.5 执行命令 wget --no-check-certificate https://www.python.org/ftp/python/3.5.0/Python-3.5.0.tgz 等待下载完成 下载完成后,执行tar -zxvf Python-3.5.0.tgz解压安装包,因文件太多,只取最后几个截图 Cd到python的解压目录下执行./configure命令,同样只取最

python与html5 websocket开发聊天对话窗

1.下载必须的包 https://github.com/Pithikos/python-websocket-server,解压缩并把文件夹名'python-websocket-server-master' 改为'websocket' 2.websocket文件夹内只保留websocket_server文件夹和server.py 3.稍微修改server.py的源码 1 from websocket_server import WebsocketServer 2 3 # Called for ev

python实现建立websocket通信

实现代码如下: #websocket协议通信 import threading import time import websocket def when_message(ws, message): print('/n接收到的消息:' + message) # 当建立连接后,死循环不断输入消息发送给服务器 # 这里需要另起一个线程 def when_open(ws): print('连接成功') def run(): while True: a = input('请输入:') ws.send(a

“Easy WebSockets with Flask and Gevent” 翻译学习笔记 ——Flask WebSocket使用快速入门

原文链接:http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent 介绍部分就先不翻了 This weekend I decided to take a short vacation from my book writing effort and spend time on a project I wanted to work on for a long time. The result of this e