supress connection errors errors

This commit is contained in:
Laila van Reenen 2024-08-15 14:51:37 +02:00
parent 45298bd360
commit 5beb79b51b
Signed by: LailaTheElf
GPG Key ID: 1F4E6EE3E6DDF769

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
import asyncio import asyncio
import websockets
from websockets.server import serve from websockets.server import serve
from datetime import datetime from datetime import datetime
import json import json
@ -20,7 +21,7 @@ async def sendToClient(client, msg):
if client['state'] != 'terminated': if client['state'] != 'terminated':
try: try:
await client['ws'].send(msg) await client['ws'].send(msg)
except ConnectionClosed: except websockets.exceptions.ConnectionClosed:
if client['state'] != 'kicked': if client['state'] != 'kicked':
client['state'] = 'terminated' client['state'] = 'terminated'
if client['boat'] is not None: if client['boat'] is not None:
@ -207,7 +208,6 @@ async def new_boat(boatId, name, ws):
async def run(ws, path): async def run(ws, path):
"""hadeler for every new websocket connection""" """hadeler for every new websocket connection"""
print("new websocket connection: " + path)
client = None client = None
async for msg in ws: async for msg in ws:
for message in msg.split("\n"): for message in msg.split("\n"):
@ -217,28 +217,37 @@ async def run(ws, path):
if len(message) == 3 and message[1] == "4675": if len(message) == 3 and message[1] == "4675":
client = await new_client(message[0], ws) client = await new_client(message[0], ws)
if client is not None: if client is not None:
async for msg in ws:
for message in msg.split("\n"): try:
if len(message) == 0: async for msg in ws:
continue for message in msg.split("\n"):
if client['state'] == 'active': if len(message) == 0:
await on_message(message, client) continue
else: if client['state'] == 'active':
break await on_message(message, client)
else:
break
except websockets.exceptions.ConnectionClosed:
print("INFO: client " + client['id'] + ": disconnected")
client['state'] = "terminated"
break break
elif (len(message) == 3 and message[1] == "3440"): elif (len(message) == 3 and message[1] == "3440"):
client = await new_boat(message[0], message[2], ws) client = await new_boat(message[0], message[2], ws)
if client is not None: if client is not None:
async for msg in ws: try:
for message in msg.split("\n"): async for msg in ws:
if len(message) == 0: for message in msg.split("\n"):
continue if len(message) == 0:
print("boat" + client['id'] + " says '" + message + "'") continue
client['log'].append({ print("boat" + client['id'] + " says '" + message + "'")
"t": datetime.timestamp(datetime.now()), client['log'].append({
"type": "rx", "t": datetime.timestamp(datetime.now()),
"msg": message "type": "rx",
}) "msg": message
})
except websockets.exceptions.ConnectionClosed:
print("INFO: boat " + client['id'] + ": disconnected")
client['state'] = "terminated"
break break
async def main(): async def main():