我有多个客户端,将它们存储在一个列表(connected)中。当一个客户端(浏览器)关闭时,我想从已连接的WebSocket列表中删除该WebSocket。
我尝试了pgjones写的方法并进行了一些小修改(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)))
在update_clients函数中,应该添加一些检测代码,以便在尝试向已经不存在的websocket发送消息时能够发现问题并将其移除。但是,目前似乎没有任何异常处理机制?!
我还尝试过:
try:
await my_websock.send(message_json)
except asyncio.CancelledError:
print('Client disconnected')
raise
但是仍然没有发生异常...
finally
块中for
循环的一个简单问题,注意break
应该在if
内部但实际上不在。 - pgjones