RODY/app/utils/websocket_tool.py

61 lines
1.8 KiB
Python
Raw Permalink Normal View History

2022-11-04 17:37:08 +08:00
"""
@Time 2022/10/12 17:55
@Auth
2022-11-24 10:58:58 +08:00
@File websocket_tool.py
@IDE PyCharm
2022-11-04 17:37:08 +08:00
@MottoABC(Always Be Coding)
@Desc
"""
import json
from typing import Union, List, Dict
from app.core.common_utils import logger
from app.utils.JSONEncodeTools import MyEncoder
2022-11-24 11:15:07 +08:00
class WebsocketUtil:
2022-11-24 15:21:00 +08:00
def __init__(self):
2022-11-25 10:07:50 +08:00
self.active_connections: List = []
self.active_connections_dist: Dict = {}
2022-11-24 10:58:58 +08:00
2022-11-04 17:37:08 +08:00
def connect(self, ws, id: str):
# 等待连接
msg = ws.receive()
# 存储ws连接对象
2022-11-25 17:39:24 +08:00
print("存储ws连接对象")
2022-11-25 10:07:50 +08:00
self.active_connections.append(ws)
if id in self.active_connections_dist:
self.active_connections_dist[id].append(ws)
2022-11-04 17:37:08 +08:00
else:
ws_list = [ws, ]
2022-11-25 10:07:50 +08:00
self.active_connections_dist[id] = ws_list
2022-11-04 17:37:08 +08:00
def disconnect(self, ws, id):
2022-11-25 10:07:50 +08:00
# ws关闭时 移除ws对象
if ws.closed:
if ws in self.active_connections_dist.values():
self.active_connections.remove(ws)
self.active_connections_dist[id].pop(ws)
2022-11-04 17:37:08 +08:00
@staticmethod
async def send_personal_message(message: str, ws):
# 发送个人消息
await ws.send(message)
2022-11-25 10:07:50 +08:00
def broadcast(self, message: str):
# 广播消息
for connection in self.active_connections:
connection.send(message)
2022-11-04 17:37:08 +08:00
def send_message_proj_json(self, message: Union[str, int, List, Dict], id: str):
# 广播该项目的消息
2022-11-25 10:07:50 +08:00
for connection in self.active_connections_dist[id]:
2022-11-24 15:21:00 +08:00
try:
connection.send(json.dumps(message, cls=MyEncoder, indent=4), )
except Exception as e:
logger.error("websocket异常断开{}", e)
2022-11-25 10:07:50 +08:00
self.disconnect(ws=connection, id=id)
2022-11-04 17:37:08 +08:00
2022-11-25 10:07:50 +08:00
manager = WebsocketUtil()