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.
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.
来源:https://stackoverflow.com/questions/14255289/twisted-reconnectingclientfactory-connection-to-different-servers