在 python 中建立和重新连接到 websocket 的更好方法是什么?

What is the better way to establish and reconnect to websocket in python?

使用下面的代码,我可以通过线程打开到不同 websocket 的连接。此连接保持稳定,直到套接字服务器重新启动。这可能超过一周。 Form then on, no new data coming in. 所以似乎重新连接效果不佳。

现在我在网上搜索了另一种语法,想知道在您看来什么是最好或更好的方法。

这里是实际运行的代码,它运行了一段时间,然后就不再运行了。我在日志中看不到任何错误代码。

ws_connections = []
# websocket-client based connection due to issue in receiving data from some urls
func_message = partial(WSClientProtocol.on_message, factory)
# websocket.enableTrace(True)
ws = websocket.WebSocketApp(
        url,
        on_message=func_message,
        on_error=WSClientProtocol.on_error,
        on_close=WSClientProtocol.on_close,
    )
    ws.on_open = WSClientProtocol.on_open
    ws_connections.append(ws)
    wst = threading.Thread(target=ws.run_forever, kwargs={'ping_interval': 5, 'ping_timeout' : 2})
    wst.daemon = True
    wst.start()

这里是我在网络研究中看到的代码,有问题你认为什么会更好。

wst = threading.Thread(target=ws.run_forever(ping_interval=70, ping_timeout=10))
wst.daemon = True
wst.start()

知道为什么我的代码停止捕获数据吗?

解决方案是:

服务器端的代理并没有关闭连接,但也没有再发送任何数据,所以为什么看起来连接关闭了,但仍然存在。

代码中的解决方案是我们开发了一个 ping/pong,我们说,如果 ping 超过一段时间没有任何响应,则重新连接。