当前位置: 首页 > article >正文

8.flask+websocket

http是短连接,无状态的。

websocket是长连接,有状态的。

flask中使用websocket

from flask import Flask, request
import asyncio
import json
import time
import websockets
from threading import Thread
from urllib.parse import urlparse, parse_qs
from functools import partial

app = Flask(__name__)

# 存储所有的WS客户端对象
# websocketClient_list = []
userId_websocketClient = dict()


async def send_message(message):
    # while True:
    #     if websocketClient_list:
    #         message = json.dumps({"time": str(time.time())}, ensure_ascii=False)
    #         await asyncio.wait([client.send(message) for client in websocketClient_list])
    #     await asyncio.sleep(1)
    # message = json.dumps({"time": str(time.time())}, ensure_ascii=False)
    # await asyncio.wait([client.send(message) for client in websocketClient_list])
    client = userId_websocketClient.get('1')
    if client:
        await asyncio.wait([client.send(message)])


async def websocket_handler(websocket, path):
    parsed_url = urlparse(path)
    query_params = parse_qs(parsed_url.query)
    # 访问参数
    user_id = query_params.get('userId')
    user_id = user_id[0] if user_id[0] else None
    if user_id:
        userId_websocketClient[user_id] = websocket

    # websocketClient_list.append(websocket)
    try:
        async for message in websocket:
            print(f"客户端发来消息:{message}")
    except websockets.ConnectionClosed:
        print("websocket closed")
    finally:
        # websocketClient_list.remove(websocket)
        del userId_websocketClient[user_id]


@app.route("/framework/pushMessage/framework_czc")
def index():
    return "WebSocket server is running. Connect to ws://<server-address>:8001/websocket"


@app.route("/send/message")
def sendMessage():
    message = "xxxxxx"

    # 创建带有参数的协程对象
    coro = partial(send_message, message)
    asyncio.set_event_loop(asyncio.new_event_loop())
    loop = asyncio.get_event_loop()
    loop.run_until_complete(coro())
    loop.close()

    return "success"


def run_websocket_server():
    asyncio.set_event_loop(asyncio.new_event_loop())
    start_server = websockets.serve(websocket_handler, "0.0.0.0", 8001)
    asyncio.get_event_loop().run_until_complete(start_server)
    # asyncio.get_event_loop().run_until_complete(send_message())
    asyncio.get_event_loop().run_forever()


if __name__ == '__main__':
    websocket_thread = Thread(target=run_websocket_server)
    websocket_thread.start()
    app.run(host="0.0.0.0", port=8000)

http://www.kler.cn/a/539870.html

相关文章:

  • C++ Primer sizeof运算符
  • 智慧停车场解决方案(文末联系,领取整套资料,可做论文)
  • Maven插件—flatten-maven-plugin:工程模块统一版本依赖
  • 【STM32F1】一种使用通用定时器实现各个通道独立输出不同指定数量脉冲的方法
  • 国产化创新 守护开放边界网络安全
  • 【web自动化】指定chromedriver以及chrome路径
  • [EAI-033] SFT 记忆,RL 泛化,LLM和VLM的消融研究
  • (原创,可用)SSH实现内外网安全穿透(安全不怕防火墙)
  • 网安加·百家讲坛 | 刘志诚:以业务为中心的网络安全挑战与机遇
  • b s架构 网络安全 网络安全架构分析
  • 【嵌入式 Linux 音视频+ AI 实战项目】瑞芯微 Rockchip 系列 RK3588-基于深度学习的人脸门禁+ IPC 智能安防监控系统
  • CSS Overflow 属性详解:控制内容溢出的利器
  • Docker、Podman 和 Containerd 三者区别
  • Windows 下搭建 googletest 测试框架(C/C++)
  • css:怎么设置图片不变形
  • jupyterLab插件开发
  • iOS AES/CBC/CTR加解密以及AES-CMAC
  • go-elasticsearch创建ik索引并进行查询操作
  • Mysql8应用架构
  • 开源身份和访问管理方案之keycloak(一)快速入门
  • CNN-day9-经典神经网络ResNet
  • 如何在React中使用Redux进行状态管理?
  • github release页面的zip和tar.gz有什么区别?
  • linux 中毒 脚本 .system 服务器中毒占用CPU,进程名称.system
  • SQLAlchemy 的内存消耗
  • React 第二十三节 useTransition Hook 的使用注意事项详解