高速公路websocket超时后如何重新连接?

2024-09-28 21:04:43 发布

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

我用高速公路连接到这样的网络插座。在

class MyComponent(ApplicationSession):

  @inlineCallbacks
  def onJoin(self, details):
    print("session ready")

    def oncounter(*args, **args2):
        print("event received: args: {} args2: {}".format(args, args2))

    try:
        yield self.subscribe(oncounter, u'topic')
        print("subscribed to topic")
    except Exception as e:
        print("could not subscribe to topic: {0}".format(e))

if __name__ == '__main__':
  addr = u"wss://mywebsocketaddress.com"
  runner = ApplicationRunner(url=addr, realm=u"realm1", debug=False, debug_app=False)
  runner.run(MyComponent)

这很好用,我可以接收信息。然而,大约3-4个小时后,信息突然停止了。websocket似乎超时了(发生了吗?),可能是由于连接问题。在

发生这种情况时,我如何自动重新连接高速公路?在


这是我的尝试,但从未调用重新连接的代码。在

^{pr2}$

我得到的错误是:

2016-10-09T21:00:40+0100 Connection to/from tcp4:xxx.xx.xx.xx:xxx was lost in a non-clean fashion: Connection lost
2016-10-09T21:00:40+0100 _connectionLost: [Failure instance: Traceback (failure with no frames): : Connection to the other side was lost in a non-clean fashion: Connection l
ost.
]
2016-10-09T21:00:40+0100 WAMP-over-WebSocket transport lost: wasClean=False, code=1006, reason="connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)"
2016-10-09T21:10:39+0100 EXCEPTION:  no messages received
2016-10-09T21:10:39+0100 Traceback (most recent call last):

Tags: toselffalsetopicdefargsconnection高速公路
3条回答

这是自动重新连接ApplicationRunner的example。启用自动重新连接的重要线路是:

runner.run(session, auto_reconnect=True)

您还需要激活自动WebSocket ping/pong(例如横杆io),以a)最小化由于超时而导致的连接中断,以及b)允许快速检测丢失的连接。在

如果使用Twisted,则可以使用ReconnectingClientFactoryThere's a simple example by the autobahn developer on github。不幸的是,似乎没有一个预构建的ApplicationRunner的实现,但是它看起来并不难实现。Here's an ^{} variant这应该是直向扭曲的。您可以跟随this issue,因为开发团队似乎希望合并重新连接的客户机。在

你试过pip3 install autobahn-autoreconnect吗?在

# from autobahn.asyncio.wamp import ApplicationRunner
from autobahn_autoreconnect import ApplicationRunner

相关问题 更多 >