Twisted: ReconnectingClientFactory connection to different servers

淺唱寂寞╮ 提交于 2019-12-19 09:19:34

问题


I have a twisted ReconnectingClientFactory and i can successfully connect to given ip and port couple with this factory. And it works well.

reactor.connectTCP(ip, port, myHandsomeReconnectingClientFactory)

In this situation, when the server is gone, myHandsomeReconnectingClientFactory tries to connect same ip and port (as expected).

My goal is, when the server which serves on given ip and port couple is gone, connecting to a backup server (which have different ip and port).

Any ideas/comments on how to achieve this goal will be appreciated.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14255289/twisted-reconnectingclientfactory-connection-to-different-servers

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