server: better error handling for connection closing
This commit is contained in:
+20
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
import asyncio
|
||||
import json, random, re, math, time, traceback
|
||||
from websockets.exceptions import ConnectionClosed, ConnectionClosedOK
|
||||
from websockets.asyncio.server import serve
|
||||
|
||||
from db import Database
|
||||
@@ -48,6 +49,12 @@ def serverError(msg,**kwargs) -> str:
|
||||
sessionUsers = {}
|
||||
sessionCreatedAccount = []
|
||||
|
||||
def forgetSession(sid):
|
||||
if sid in sessionUsers:
|
||||
del sessionUsers[sid]
|
||||
if sid in sessionCreatedAccount:
|
||||
sessionCreatedAccount.remove(sid)
|
||||
|
||||
async def handleCommand(ws,cmd):
|
||||
global sessionUsers
|
||||
print(f"recieved command: {cmd} (from {id(ws)})")
|
||||
@@ -59,6 +66,8 @@ async def handleCommand(ws,cmd):
|
||||
match cmd["type"]:
|
||||
case "ping":
|
||||
return await ws.send(response("Pong!"))
|
||||
|
||||
# accounts
|
||||
case "createuser":
|
||||
if uid != None:
|
||||
return await ws.send(clientError("You are already logged in."))
|
||||
@@ -163,9 +172,19 @@ async def serveClient(ws):
|
||||
except Exception as e:
|
||||
traceback.print_exception(e)
|
||||
await ws.send(serverError(f"Cannot process command ({cmd["type"]})"))
|
||||
except json.decoder.JSONDecodeError:
|
||||
await ws.send(serverError("Cannot process JSON."))
|
||||
except ConnectionClosedOK:
|
||||
print(f"connection {id(ws)} has closed")
|
||||
forgetSession(id(ws))
|
||||
break
|
||||
except ConnectionClosed as e:
|
||||
print(f"connection {id(ws)} has closed with a non-OK exit code:")
|
||||
traceback.print_exception(e)
|
||||
break
|
||||
except Exception as e:
|
||||
traceback.print_exception(e)
|
||||
await ws.send(serverError("Cannot process JSON."))
|
||||
await ws.send(serverError("Cannot parse command."))
|
||||
|
||||
async def main():
|
||||
async with serve(serveClient, "", 30341) as server:
|
||||
|
||||
Reference in New Issue
Block a user