使用高速公路重新连接到websocket

2024-10-06 12:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过使用它们的websocketapi从Poloniex API获取数据。我用的是AutoBahn Python websocket library。在

目前,我正在使用下面的代码打印可用的票证数据。这样做很好,但时间不长。每隔12-36小时,它就会停止输出(我想当Poloniex重启服务器时)。在

有没有一种优雅的方法来检查ApplicationRunner是否仍然连接,并在断开连接时重新启动它?onDisconnect未触发。当我运行脚本时,进程不会在套接字停止接收数据时终止,因此我认为事件循环不会停止。在

from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine
import asyncio
from datetime import datetime

class PoloniexComponent(ApplicationSession):
    def onConnect(self):
        self.join(self.config.realm)

    @coroutine
    def onJoin(self, details):
        def onTicker(*args):
            print("{}: {}".format(datetime.utcnow(), str(args)))
        try:
            yield from self.subscribe(onTicker, 'ticker')
        except Exception as e:
            print("Could not subscribe to topic:", e)

    def onDisconnect(self):
        asyncio.get_event_loop().stop()


def main():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexComponent)

if __name__ == "__main__":
    main()

Tags: fromimportselfasynciodatetimemaindefpoloniex
1条回答
网友
1楼 · 发布于 2024-10-06 12:33:43

由于WebSocket连接是持久的,在没有实际通信量的情况下不会发送数据,因此不会发现底层连接已被终止(Poloniex WebSocket服务器重新启动时会发生这种情况)——

为了能够对断开连接做出快速和决定性的响应,需要在服务器端启用WebSocket自动ping。[source]

我不知道,但假设马球没有激活这个选项。。。在

但您可以使用以下方法构建自己的活动ping版本:

创建另一个ApplicationRunner实例(名为“runner_watcher”),尝试用它订阅一个新主题,完成后关闭该实例,然后等待N秒并重新启动该过程,等等。。在

当您的“runner_watcher”实例上引发异常(“无法订阅主题”)时,您可能会假设服务器已关闭…,因此您将强制停止主应用程序runner,并在服务器返回时(在执行“runner_watcher”期间不再引发异常),您可以假设服务器重新启动,然后重新启动主ApplicationRunner

我同意这种方法是肮脏的(不优雅),但它可能有效

2015年,高速公路尚未实施自动重新连接,但目前正在进行中。在

相关问题 更多 >