使用Python/Quart和Websockets检测客户端断开连接

3

我有多个客户端,将它们存储在一个列表(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

但是仍然没有发生异常...



这里不清楚你认为出了什么问题,它是否按照你的预期工作? - pgjones
嗨pgjones,感谢您的回复。 我想知道在服务器端当客户端不再存在时会发生什么。 这样我就可以从“已连接”列表中删除客户端。 现在发生的情况是,“已连接”列表随着时间的推移在生产中不断增长。每当一个连接消失时,它仍然留在列表中。当客户端创建新连接时,它会像应该添加一样。“已连接”的目的是仅在列表中拥有活动的Websockets /客户端。 - socialb
这可能是finally块中for循环的一个简单问题,注意break应该在if内部但实际上不在。 - pgjones
哦,我明白了,那是一个复制粘贴问题到stackoverflow。我测试了一些更多的东西。在我的本地机器上它工作正常,所以当一个浏览器选项卡关闭时,它会被删除。但在我的AWS ec2上不行。 - socialb
1个回答

2

将quart和hypercorn更新到0.9/0.6版本后,代码可以在电脑的浏览器(Firefox,Chrome)上运行。

但是,当我使用建立连接并在之后关闭它时,连接并没有被移除!

有什么建议吗?

注:Original Answer翻译成"最初的回答"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接