Twisted: ReconnectingClientFactory connection to different servers

半城伤御伤魂 提交于 2019-12-01 06:51:51

Id try something like:

class myHandsomeReconnectingClientFactory(protocol.ReconnectingClientFactory):

    def __init_(self, hosts):
        # hosts should be a list of tuples (host, port)
        self._hosts = hosts

    def clientConnectionFailed(self, connector, reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def clientConnectionLost(self, connector, unused_reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def _try_next_host(self, connector):
        # round robing of servers
        to_try = self._hosts.pop(0)
        self._hosts.append(to_try)
        connector.host, connector.port = to_try
        self.connector = connector
        self.retry()

I haven't actually tested it, but at least it should give you a good starting point. Good uck.

ReconnectingClientFactory doesn't have this capability. You can build your own factory which implements this kind of reconnection logic, mostly by hooking into the clientConnectionFailed factory method. When this is called and the reason seems to you like that justifies switching servers (eg, twisted.internet.error.ConnectionRefused), pick the next address on your list and use the appropriate reactor.connectXYZ method to try connecting to it.

You could also try constructing this as an endpoint (which is the newer high-level connection setup API that is preferred by some), but handling reconnection with endpoints is not yet a well documented topic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!