# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: websocket_manager Description : Author : qiangyanwen date: 2022/12/6 ------------------------------------------------- """ from fastapi import WebSocket from typing import List class WebsocketManager: def __init__(self): self.active_connections: List[WebSocket] = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) async def disconnect(self, websocket: WebSocket): await websocket.close() self.active_connections.remove(websocket) @staticmethod async def send_message(message: str, websocket: WebSocket): await websocket.send_text(message) @staticmethod async def send_json(message: str, websocket: WebSocket): await websocket.send_json(message) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) manager = WebsocketManager()