Handle abrupt WebSocket disconnect (e.g. Safari tab close)
Catch ConnectionClosed in User.send() and handler_recv() so that an unclean client disconnect no longer produces "Task exception was never retrieved" / "connection handler failed" log noise. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SH2D4LRuCnhLSzoYerAfJX
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
import websockets.exceptions
|
||||||
from ws.server.ws_server import WsServer
|
from ws.server.ws_server import WsServer
|
||||||
from ws.user import User, UserSet, update
|
from ws.user import User, UserSet, update
|
||||||
from ws.connection import IConnection
|
from ws.connection import IConnection
|
||||||
@@ -31,14 +32,17 @@ class WsServerMultiUser(WsServer):
|
|||||||
await self.notify_users()
|
await self.notify_users()
|
||||||
|
|
||||||
async def handler_recv(self, websocket, path):
|
async def handler_recv(self, websocket, path):
|
||||||
while True:
|
try:
|
||||||
data = await websocket.recv()
|
while True:
|
||||||
usr = self.USERS.get(websocket)
|
data = await websocket.recv()
|
||||||
processed = await usr.process(data)
|
usr = self.USERS.get(websocket)
|
||||||
if processed:
|
processed = await usr.process(data)
|
||||||
await usr.send(self.global_state)
|
if processed:
|
||||||
else:
|
await usr.send(self.global_state)
|
||||||
await self.listener.on_recv(data)
|
else:
|
||||||
|
await self.listener.on_recv(data)
|
||||||
|
except websockets.exceptions.ConnectionClosed:
|
||||||
|
pass
|
||||||
|
|
||||||
async def handler_send(self, websocket, path):
|
async def handler_send(self, websocket, path):
|
||||||
while True:
|
while True:
|
||||||
|
|||||||
+5
-1
@@ -1,5 +1,6 @@
|
|||||||
import dpath.util as dp
|
import dpath.util as dp
|
||||||
import json
|
import json
|
||||||
|
import websockets.exceptions
|
||||||
|
|
||||||
|
|
||||||
def update(d, u, only_existing=True):
|
def update(d, u, only_existing=True):
|
||||||
@@ -26,7 +27,10 @@ class User:
|
|||||||
msg = dp.search(data, path)
|
msg = dp.search(data, path)
|
||||||
result.update(msg)
|
result.update(msg)
|
||||||
if len(result) != 0:
|
if len(result) != 0:
|
||||||
await self.socket.send(json.dumps(result))
|
try:
|
||||||
|
await self.socket.send(json.dumps(result))
|
||||||
|
except websockets.exceptions.ConnectionClosed:
|
||||||
|
pass
|
||||||
|
|
||||||
async def process(self, data):
|
async def process(self, data):
|
||||||
handled = True
|
handled = True
|
||||||
|
|||||||
Reference in New Issue
Block a user