zoukankan      html  css  js  c++  java
  • Flask+gevent-websocket模块实现websocket

    后端代码:

    from flask import Flask,request
    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    from geventwebsocket.websocket import WebSocket   #这条做语法提示用
    
    app = Flask(__name__)
    
    @app.route('/conn')
    def index():
        #获取请求原始数据
        user_socket = request.environ
        #获取websocket对象
        websocket_obj = user_socket['wsgi.websocket'] #type:WebSocket
    
        while True:  #循环监听
            # 监听链接,接收数据
            msg = websocket_obj.receive()
            print(msg)
            websocket_obj.send(msg+'youtoo')
    
    
    if __name__ == '__main__':
        # app.run()
        #在APP外封装websocket
        http_serv = WSGIServer(("0.0.0.0",5000),app,handler_class=WebSocketHandler)
        # 启动服务
        http_serv.serve_forever()

    模板代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>websocket客户端</title>
    </head>
    <body>
    
    
    <script type="application/javascript">
        var ws = new WebSocket('ws://127.0.0.1:5000/conn');   //建立websocket链接
        //接收数据
        ws.onmessage = function (messageEvent) {
            console.log(messageEvent.data)
        }
    </script>
    </body>
    </html>
  • 相关阅读:
    tablespaces
    转 房价
    Duplicate a whole line in Vim
    Dubbo+JStorm
    replace all
    ORACLE 最后表数据更新的时间
    list reverse
    python IDE
    string 方法
    java JIT AOT
  • 原文地址:https://www.cnblogs.com/jayxuan/p/11385240.html
Copyright © 2011-2022 走看看