我有多个客户,我存储在一个列表中(已连接)。当客户端(浏览器)关闭时,我想从连接的 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
......
在代码中进一步......
......
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
但是还是没有出现异常...