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)