From 8bc8a37edd1d0ae5c5f6f6f9d373cfc103983ac3 Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Sat, 25 Mar 2023 16:14:05 +0100 Subject: [PATCH] WS game-state URI --- README.md | 11 ++--------- hopper/ws_client.py | 11 ++++++----- ws_server.py | 2 +- 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index ded394d..34bad7d 100644 --- a/README.md +++ b/README.md @@ -253,17 +253,10 @@ Response body: ### WS Data format - json -General data format: -```json -{ - "command": "command", - "data": {} -} -``` -### Game info structure +### Game state structure -Command: `gameInfo` +URI: `/game-state` Data: ```json diff --git a/hopper/ws_client.py b/hopper/ws_client.py index 73abdc8..1d6444c 100644 --- a/hopper/ws_client.py +++ b/hopper/ws_client.py @@ -3,14 +3,15 @@ import logging from contextlib import asynccontextmanager import websockets +from websockets.exceptions import ConnectionClosed from hopper.models.ws_dto import GameStateDto from settings import settings @asynccontextmanager -async def create_ws_client() -> websockets.WebSocketServerProtocol: - ws_uri = f"ws://{settings.ws_server.HOST}:{settings.ws_server.PORT}" +async def create_ws_client(path: str) -> websockets.WebSocketServerProtocol: + ws_uri = f"ws://{settings.ws_server.HOST}:{settings.ws_server.PORT}{path}" async with websockets.connect(uri=ws_uri) as websocket: yield websocket @@ -20,7 +21,7 @@ async def ws_send_game_state() -> None: from hopper.api.dependencies import get_game_engine try: - async with create_ws_client() as websocket: + async with create_ws_client("/game-state") as websocket: engine = get_game_engine() game_state = GameStateDto( @@ -30,5 +31,5 @@ async def ws_send_game_state() -> None: layers=engine.get_board_layout().layers, ) await websocket.send(json.dumps(game_state.dict())) - except OSError as ex: - logging.error(f"Error sending WS state: {ex}") \ No newline at end of file + except (OSError, ConnectionClosed) as ex: + logging.error(f"Error sending WS state: {ex}") diff --git a/ws_server.py b/ws_server.py index e5ac88c..abfbb1f 100644 --- a/ws_server.py +++ b/ws_server.py @@ -22,7 +22,7 @@ async def ws_handler(websocket: WebSocketServerProtocol): try: async for message in websocket: - logging.debug(f"Received message: {message}") + logging.debug(f"Received message on {websocket.path}: {message}") broadcast_clients = [client for client in connected_clients if client.id != websocket.id] if broadcast_clients: logging.debug(f"Broadcast message to clients: {broadcast_clients}")