fix player disconnect bug (#17)
* fixi fix fix * make sure players websocket objects are properly destroyed * broadcast gamestate after disconnect
This commit is contained in:
1 parent
fb74527e82
commit
a8777035f8
1 file changed
+10
-5
+10
-5
@@ -24,7 +24,7 @@ def is_spectator() -> bool:
|
||||
|
||||
|
||||
def get_players() -> list[T_PlayerStateDict]:
|
||||
query = filter(lambda x: not x.is_spectator, PLAYERS)
|
||||
query = filter(lambda x: not x.is_spectator and not x.is_disconnected, PLAYERS)
|
||||
|
||||
players: list[T_PlayerStateDict] = []
|
||||
|
||||
@@ -35,7 +35,7 @@ def get_players() -> list[T_PlayerStateDict]:
|
||||
|
||||
|
||||
def get_spectators() -> list[T_SpectatorStateDict]:
|
||||
query = filter(lambda x: x.is_spectator, PLAYERS)
|
||||
query = filter(lambda x: x.is_spectator and not x.is_disconnected, PLAYERS)
|
||||
|
||||
players: list[T_SpectatorStateDict] = []
|
||||
|
||||
@@ -62,6 +62,8 @@ async def broadcast(message):
|
||||
|
||||
|
||||
async def handler(websocket: ServerConnection):
|
||||
player: Player | None = None
|
||||
|
||||
try:
|
||||
async for msg in websocket:
|
||||
raw_action = json.loads(msg)
|
||||
@@ -129,9 +131,6 @@ async def handler(websocket: ServerConnection):
|
||||
except exceptions.ConnectionClosed:
|
||||
print("client has disconnected")
|
||||
|
||||
if player is not None:
|
||||
player.disconnect()
|
||||
|
||||
except Exception as exception:
|
||||
print(str(exception))
|
||||
await websocket.close(1011)
|
||||
@@ -140,6 +139,12 @@ async def handler(websocket: ServerConnection):
|
||||
print("exited client polling loop")
|
||||
await websocket.close(1000)
|
||||
|
||||
finally:
|
||||
for player in PLAYERS:
|
||||
if player.websocket is not None and player.websocket.id == websocket.id:
|
||||
player.disconnect()
|
||||
await broadcast(get_gamestate())
|
||||
|
||||
|
||||
async def main():
|
||||
async with serve(handler, "localhost", 8888) as server:
|
||||
|
||||
Reference in new issue
Block a user