• 基于Flask框架使用Web Socket实现收发机制


    前端js的收发机制:

        // 新建一个websocket链接
           var ws = new WebSocket("%s://%s/foobar/");

      // 链接成功时,可以在函数中做一些操作

      ws.onopen = function() {}


           // 接收后端发送过来的数据
      ws.onmessage = function(e) {}


      // 进行异常处理
      ws.onerror = function(e) {}


      // 关闭链接
      ws.onclose = function(e) {}


            // 向后端发送数据
      s.send(value);

    后端代码:

    from flask import Flask,request
    from geventwebsocket.handler import WebSocketHandler
    from gevent.pywsgi import WSGIServer
    
    from geventwebsocket.websocket import WebSocket  # 做语法提示用的
    
    app = Flask(__name__)  # type: Flask
    
    
    @app.route("/ws")
    def web_sck():
        # print(request.environ)  #  打印的原始请求数据
        # 这个东西其实就是WebSocket的长链接
        user_socket = request.environ.get("wsgi.websocket")   # type: WebSocket
        while 1:
            msg = user_socket.receive()  # 接收客户端传入数据
            # 在浏览器中content的中输入ws ,readyState如果为1 表示连接成功,如果等于3表示,连接成功后又断开了连接,0 表示没有开启
            print(msg)
            try:
                user_socket.send(msg)  # 把接收到的数据,返回给前端
            except:
                return
    
    if __name__ == "__main__":
        # app.run("0.0.0.0",8000,debug=True)
        http_serve = WSGIServer(("0.0.0.0",8000),app,handler_class=WebSocketHandler)
        http_serve.serve_forever()  # 启动这个web-server请求

    前端代码:

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>多人聊天</title>
    </head>
    <body>
    <script type="application/javascript">
        var ws = new WebSocket("ws://127.0.0.1:8000/ws") ; // 指定发送的链接地址
        ws.onopen = function(){
            ws.send("hello")
        };
    
        // 前端接收消息   ws_info 接收数据的容器
        ws.onmessage = function (ws_info) {
            console.log(ws_info.data)
        }
    </script>
    </body>
    </html>
  • 相关阅读:
    挖矿是如何产生比特币的?
    影响世界的100个管理定律
    震撼人心的战争类背景音乐
    一个美国女警的工作记录(转载
    李昌镐:苍老的青春(转载)
    博主简介
    python 中判断变量是否定义
    Reading geometries
    Writing geometries
    Accessing data using cursors
  • 原文地址:https://www.cnblogs.com/mwhylj/p/10157133.html
Copyright © 2020-2023  润新知