I have multiple clients, which I store in a list (connected). When a client (browser) is closed, i want to remove this websocket from the list of connected websockets.
I've tried the method that pgjones wrote with some little alteration (https://medium.com/@pgjones/websockets-in-quart-f2067788d1ee):
def collect_websocket(func):
@wraps(func)
async def wrapper(*args, **kwargs):
global connected
data = await websocket.receive()
data_json = json.loads(data)
if data_json['msg_type'] == 'client_connect':
if "id" in data_json:
new_client = Client(data_json['id'], False, websocket._get_current_object())
connected.add(new_client)
try:
return await func(*args, **kwargs)
except Exception as e:
connected.remove(websocket._get_current_object())
finally:
for connect in connected:
if connect.ws == websocket._get_current_object():
connected.remove(connect)
break
return wrapper
...
further in the code...
...
async def update_clients(self, input_survey):
try:
for client in connected:
if client.survey_id == input_survey.identifier:
my_websock = client.ws
message = { ... some message...
}
message_json = json.dumps(message)
await my_websock.send(message_json)
except:
var = traceback.format_exc()
constants.raven_client.captureException()
self.logger.error('ERROR updating clients: {}'.format(str(var)))
In update_clients there should be some detection that the sending to a websocket that doesn't exist anymore goes wrong... and then remove it. But there is no exception...?!
I also tried to:
try:
await my_websock.send(message_json)
except asyncio.CancelledError:
print('Client disconnected')
raise
But still no exception occurred...