| from fastapi import FastAPI, WebSocket, WebSocketDisconnect |
| from typing import List |
| import asyncio |
|
|
| app = FastAPI() |
|
|
| |
| active_connections: List[WebSocket] = [] |
|
|
| @app.websocket("/ws") |
| async def websocket_endpoint(websocket: WebSocket): |
| |
| await websocket.accept() |
| active_connections.append(websocket) |
| print(f"New client connected! Total clients: {len(active_connections)}") |
|
|
| try: |
| while True: |
| |
| data = await websocket.receive_text() |
| print(f"Received message: {data}") |
|
|
| |
| await broadcast_message(f"Broadcast: {data}") |
| |
| |
| await websocket.send_text(f"Echo: {data}") |
| except WebSocketDisconnect: |
| |
| active_connections.remove(websocket) |
| print(f"Client disconnected! Total clients: {len(active_connections)}") |
|
|
| async def broadcast_message(message: str): |
| """Helper function to broadcast a message to all active WebSockets.""" |
| |
| for connection in active_connections: |
| try: |
| await connection.send_text(message) |
| except Exception as e: |
| |
| print(f"Error sending message: {e}") |
| active_connections.remove(connection) |
|
|