Cleanups
This commit is contained in:
@ -12,20 +12,20 @@ from settings import settings
|
||||
|
||||
|
||||
class WSServer(Thread):
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
self.connected_clients = set[WebSocketServerProtocol]()
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
async def handler(self, websocket: WebSocketServerProtocol) -> None:
|
||||
"""New handler instance spawns for each connected client"""
|
||||
self.connected_clients.add(websocket)
|
||||
logging.info(f"Add client: {websocket.id}")
|
||||
|
||||
try:
|
||||
# send initial game state to connected client
|
||||
await self.send_game_state_to_client(websocket)
|
||||
# loop and do nothing while client is connected
|
||||
connected = True
|
||||
while connected:
|
||||
try:
|
||||
message = await websocket.recv()
|
||||
# we're expecting nothing from client, but read if client sends a message
|
||||
await websocket.recv()
|
||||
except ConnectionClosedOK:
|
||||
connected = False
|
||||
finally:
|
||||
@ -49,11 +49,13 @@ class WSServer(Thread):
|
||||
async def send_game_state_to_client(
|
||||
self, websocket: WebSocketServerProtocol
|
||||
) -> None:
|
||||
"""Send game state to the client"""
|
||||
message = self._create_game_state_message()
|
||||
logging.debug(f"Sending game state to client: {websocket.id}")
|
||||
await websocket.send(message)
|
||||
|
||||
async def send_game_state(self) -> None:
|
||||
"""Broadcast game state to all connected clients"""
|
||||
if not self.connected_clients:
|
||||
return
|
||||
|
||||
@ -77,4 +79,5 @@ class WSServer(Thread):
|
||||
await asyncio.Future() # run forever
|
||||
|
||||
def run(self) -> None:
|
||||
self.connected_clients = set[WebSocketServerProtocol]()
|
||||
asyncio.run(self.run_async())
|
||||
|
||||
Reference in New Issue
Block a user