Update server_old.py
Browse files- server_old.py +72 -22
server_old.py
CHANGED
|
@@ -11,13 +11,13 @@ app = FastAPI()
|
|
| 11 |
# Configure CORS
|
| 12 |
app.add_middleware(
|
| 13 |
CORSMiddleware,
|
| 14 |
-
allow_origins=["*"],
|
| 15 |
allow_credentials=True,
|
| 16 |
-
allow_methods=["*"],
|
| 17 |
-
allow_headers=["*"],
|
| 18 |
)
|
| 19 |
|
| 20 |
-
# Serve static files
|
| 21 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 22 |
|
| 23 |
# Set up Jinja2 templates
|
|
@@ -44,40 +44,90 @@ async def get_map_by_normalized_name(request: Request, normalized_name: str):
|
|
| 44 |
|
| 45 |
class ConnectionManager:
|
| 46 |
def __init__(self):
|
| 47 |
-
self.
|
|
|
|
| 48 |
|
| 49 |
async def connect(self, websocket: WebSocket):
|
| 50 |
await websocket.accept()
|
| 51 |
-
self.active_connections.append(websocket)
|
| 52 |
-
print("active_connections:", self.active_connections)
|
| 53 |
|
| 54 |
def disconnect(self, websocket: WebSocket):
|
| 55 |
-
self.
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
manager = ConnectionManager()
|
| 68 |
|
| 69 |
|
| 70 |
-
@app.websocket("/
|
| 71 |
-
async def websocket_endpoint(websocket: WebSocket
|
| 72 |
await manager.connect(websocket)
|
| 73 |
try:
|
| 74 |
while True:
|
| 75 |
data = await websocket.receive_text()
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
except WebSocketDisconnect:
|
| 78 |
manager.disconnect(websocket)
|
| 79 |
-
await manager.broadcast(json.dumps({"type": "client_info", "data": f"Client #{client_id} left the chat"}))
|
| 80 |
|
| 81 |
|
| 82 |
if __name__ == "__main__":
|
| 83 |
-
uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
| 11 |
# Configure CORS
|
| 12 |
app.add_middleware(
|
| 13 |
CORSMiddleware,
|
| 14 |
+
allow_origins=["*"],
|
| 15 |
allow_credentials=True,
|
| 16 |
+
allow_methods=["*"],
|
| 17 |
+
allow_headers=["*"],
|
| 18 |
)
|
| 19 |
|
| 20 |
+
# Serve static files
|
| 21 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 22 |
|
| 23 |
# Set up Jinja2 templates
|
|
|
|
| 44 |
|
| 45 |
class ConnectionManager:
|
| 46 |
def __init__(self):
|
| 47 |
+
self.groups: dict[str, set[WebSocket]] = {}
|
| 48 |
+
self.connections: dict[WebSocket, str] = {}
|
| 49 |
|
| 50 |
async def connect(self, websocket: WebSocket):
|
| 51 |
await websocket.accept()
|
|
|
|
|
|
|
| 52 |
|
| 53 |
def disconnect(self, websocket: WebSocket):
|
| 54 |
+
if websocket in self.connections:
|
| 55 |
+
group_name = self.connections[websocket]
|
| 56 |
+
self.remove_from_group(websocket, group_name)
|
| 57 |
+
|
| 58 |
+
async def join_group(self, websocket: WebSocket, group_name: str):
|
| 59 |
+
# Remove from previous group if exists
|
| 60 |
+
if websocket in self.connections:
|
| 61 |
+
old_group = self.connections[websocket]
|
| 62 |
+
self.remove_from_group(websocket, old_group)
|
| 63 |
+
|
| 64 |
+
# Add to new group
|
| 65 |
+
if group_name not in self.groups:
|
| 66 |
+
self.groups[group_name] = set()
|
| 67 |
+
self.groups[group_name].add(websocket)
|
| 68 |
+
self.connections[websocket] = group_name
|
| 69 |
+
print(f"Client joined group '{group_name}'")
|
| 70 |
+
|
| 71 |
+
def remove_from_group(self, websocket: WebSocket, group_name: str):
|
| 72 |
+
if group_name in self.groups and websocket in self.groups[group_name]:
|
| 73 |
+
self.groups[group_name].remove(websocket)
|
| 74 |
+
if len(self.groups[group_name]) == 0:
|
| 75 |
+
del self.groups[group_name]
|
| 76 |
+
print(f"Group '{group_name}' deleted (no members)")
|
| 77 |
+
if websocket in self.connections:
|
| 78 |
+
del self.connections[websocket]
|
| 79 |
+
print(f"Client removed from group '{group_name}'")
|
| 80 |
+
|
| 81 |
+
async def broadcast_to_group(self, message: str, group_name: str):
|
| 82 |
+
if group_name in self.groups:
|
| 83 |
+
for connection in self.groups[group_name]:
|
| 84 |
+
await connection.send_text(message)
|
| 85 |
|
| 86 |
|
| 87 |
manager = ConnectionManager()
|
| 88 |
|
| 89 |
|
| 90 |
+
@app.websocket("/ws")
|
| 91 |
+
async def websocket_endpoint(websocket: WebSocket):
|
| 92 |
await manager.connect(websocket)
|
| 93 |
try:
|
| 94 |
while True:
|
| 95 |
data = await websocket.receive_text()
|
| 96 |
+
try:
|
| 97 |
+
message = json.loads(data)
|
| 98 |
+
# Handle join messages
|
| 99 |
+
if message.get('type') == 'join':
|
| 100 |
+
group_name = message.get('group')
|
| 101 |
+
if group_name:
|
| 102 |
+
await manager.join_group(websocket, group_name)
|
| 103 |
+
else:
|
| 104 |
+
error = json.dumps({
|
| 105 |
+
"type": "error",
|
| 106 |
+
"message": "Missing group name in join request"
|
| 107 |
+
})
|
| 108 |
+
await websocket.send_text(error)
|
| 109 |
+
|
| 110 |
+
# Broadcast all other messages to the group
|
| 111 |
+
else:
|
| 112 |
+
if websocket in manager.connections:
|
| 113 |
+
group_name = manager.connections[websocket]
|
| 114 |
+
await manager.broadcast_to_group(data, group_name)
|
| 115 |
+
else:
|
| 116 |
+
error = json.dumps({
|
| 117 |
+
"type": "error",
|
| 118 |
+
"message": "Join a group before sending messages"
|
| 119 |
+
})
|
| 120 |
+
await websocket.send_text(error)
|
| 121 |
+
|
| 122 |
+
except json.JSONDecodeError:
|
| 123 |
+
# Handle non-JSON messages by broadcasting directly
|
| 124 |
+
if websocket in manager.connections:
|
| 125 |
+
group_name = manager.connections[websocket]
|
| 126 |
+
await manager.broadcast_to_group(data, group_name)
|
| 127 |
+
|
| 128 |
except WebSocketDisconnect:
|
| 129 |
manager.disconnect(websocket)
|
|
|
|
| 130 |
|
| 131 |
|
| 132 |
if __name__ == "__main__":
|
| 133 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|