WS game-state URI
This commit is contained in:
11
README.md
11
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
|
||||
|
||||
@ -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:
|
||||
except (OSError, ConnectionClosed) as ex:
|
||||
logging.error(f"Error sending WS state: {ex}")
|
||||
@ -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}")
|
||||
|
||||
Reference in New Issue
Block a user