try and finally for disconnects

master
chimchooree 2 years ago
parent 04735eefa2
commit e929599eb8

@ -5,20 +5,31 @@ import websockets
connected = [] connected = []
IDs = {} IDs = {}
async def handler(websocket): async def check(websocket):
await websocket.send(json.dumps({"type": "test", "message": "test packet from server"})) await websocket.send(json.dumps({"type": "test", "message": "test packet from server"}))
async for original in websocket: async for original in websocket:
packet = json.loads(original) packet = json.loads(original)
print(packet) print(packet)
if packet["type"] == "user_joined": if packet["type"] == "user_joined":
IDs[websocket] = packet["name"] IDs[websocket] = packet["name"]
connected.append(websocket)
websockets.broadcast(connected, json.dumps({"type": "server_message", "message": IDs[websocket] + " joined"})) websockets.broadcast(connected, json.dumps({"type": "server_message", "message": IDs[websocket] + " joined"}))
elif packet["type"] == "shout" or packet['type'] == "server_message": elif packet["type"] == "shout" or packet['type'] == "server_message":
websockets.broadcast(connected, json.dumps({"type": "shout", "name": IDs[websocket], "message": packet["message"]})) websockets.broadcast(connected, json.dumps({"type": "shout", "name": IDs[websocket], "message": packet["message"]}))
async def handler(websocket):
while True:
try:
connected.append(websocket)
await check(websocket)
except websockets.exceptions.ConnectionClosed:
websockets.broadcast(connected, json.dumps({"type": "server_message", "message": IDs[websocket] + " joined"}))
break
finally:
if websocket in connected:
connected.remove(websocket)
async def main(): async def main():
async with websockets.serve(handler, "", 8080): async with websockets.serve(handler, "", 8080):
await asyncio.Future() # run forever await asyncio.Future() # run forever

Loading…
Cancel
Save