초기화
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import logging
|
||||
from typing import List
|
||||
from fastapi import WebSocket, WebSocketDisconnect
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class ConnectionManager:
|
||||
def __init__(self):
|
||||
# 활성화된 웹소켓 커넥션 목록 관리
|
||||
self.active_connections: List[WebSocket] = []
|
||||
|
||||
async def connect(self, websocket: WebSocket):
|
||||
await websocket.accept()
|
||||
self.active_connections.append(websocket)
|
||||
logger.info(f"[WS] Client connected. Total active connections: {len(self.active_connections)}")
|
||||
|
||||
def disconnect(self, websocket: WebSocket):
|
||||
if websocket in self.active_connections:
|
||||
self.active_connections.remove(websocket)
|
||||
logger.info(f"[WS] Client disconnected. Total active connections: {len(self.active_connections)}")
|
||||
|
||||
async def broadcast(self, message: dict):
|
||||
"""
|
||||
접속한 모든 웹 브라우저 클라이언트에게 JSON 데이터를 전송합니다.
|
||||
"""
|
||||
if not self.active_connections:
|
||||
return
|
||||
|
||||
logger.debug(f"[WS BROADCAST] Broadcasting message to {len(self.active_connections)} clients.")
|
||||
disconnected_clients = []
|
||||
for connection in self.active_connections:
|
||||
try:
|
||||
await connection.send_json(message)
|
||||
except Exception as e:
|
||||
logger.warning(f"[WS BROADCAST] Failed to send message to client, marked for cleanup: {e}")
|
||||
disconnected_clients.append(connection)
|
||||
|
||||
# 오류가 난 비정상 커넥션 정리
|
||||
for conn in disconnected_clients:
|
||||
self.disconnect(conn)
|
||||
|
||||
# 전역 싱글톤 매니저 인스턴스
|
||||
ws_manager = ConnectionManager()
|
||||
Reference in New Issue
Block a user