【flask】基于geventwebsocket实现websocket功能

1、客户端向服务端推数据​​​​​​​

WSGIServer默认处理的是http请求,路由视图中可以正常使用http,但是在使用ws协议时务必在视图函数通过request.environ.get('wsgi.websocket')获取与客户端的ws连接websocket_obj ,通过连接websocket_obj 进行websocket_obj .recive()/websocket_obj .send()通信,这个方法会对字符串自动进行编解码。

server端代码

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

浏览器提供了websocket客户端,直接new创建websocket连接ws,通过ws.onmessage=function (MessageEvent){}监听执行回调函数获取信息MessageEvent.data,通过ws.send()发送信息

client端代码

<!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.onopen=function () {
        const arr = [1, 2, 3,4,5,6,7,8,9];
        for(let i = 0; i< arr.length; i++)
        {
            ws.send(arr[i]);
        }
    }
    //接收数据
    ws.onmessage = function (messageEvent) {
        console.log(messageEvent.data)
    }
</script>
</body>
</html>

运行结果图

 2、服务端向客户端推数据

client端代码

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["wsgi.websocket"]  # type:WebSocket
    user_msg = user_socket.receive()
    if user_msg=="1":
        print("接收到数据啦")
        for i in range(1000):
            user_socket.send(str(i)+'yoyo')
        print("数据发送完毕")
        return "OK"

if __name__ == '__main__':
    # app.run()
    #在APP外封装websocket
    http_serv = WSGIServer(("0.0.0.0",5000),app,handler_class=WebSocketHandler)
    # 启动服务
    http_serv.serve_forever()

server端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket客户端</title>
</head>
<body>
<input type="text" id="idname">
<script type="application/javascript">
    // 客户端接收数据
    var ws = new WebSocket("ws://127.0.0.1:5000/conn");
    console.log(ws);
    ws.onopen = function () {
        alert("websocket is 就绪");
        ws.send("1")
        console.log(ws);
    };
    ws.onmessage = function (ws_status) {
        document.getElementById("idname").value=ws_status.data;
        console.log(ws_status.data)
    };
</script>
</body>
</html>

运行结果图

 参考链接:python flask框架上增加websocket的功能 --> fearlazy

flask之gevent-websocket的IO多路复用长连接通信 - 笑得好美 - 博客园 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值