在重新连接的客户端工厂中切换目标

时间:2012-09-10 21:22:45

标签: python twisted

我有一个基于twisted.internet.protocol.ReconnectingClientFactory的客户端。我希望当达到当前服务器上的重试次数时,此客户端切换到不同的服务器;我连接到server1,它失败5次,我切换到server2

我目前通过在重新连接工厂的重试功能中更改目标主机和端口来实现此目的:

class Factory(twisted.internet.protocol.ReconnectingClientFactory, object):

    def retry(self, connector=None):
    """ Retry to connect to the host. After the Max retries count is reached, 
    switch to an alternative host if available """

    if connector is None:
        if self.connector is None:
            raise ValueError("no connector to retry")
        else:
            connector = self.connector


    if self.retries >= self.maxRetries and self.alt_host is not None:
        # Try to connect to alternate server
        currrent_host, current_port = connector.host, connector.port
        connector.host, connector.port = self.alt_host, self.alt_port
        self.alt_host, self.alt_port = currrent_host, current_port
        print ("Switching to server: %s:%s" % (connector.host, connector.port))
        # Connector gets new address
        connector.getDestination() 
        # reset number of retries
        self.resetDelay()                

    super(Factory, self).retry(connector)

    def addHost(self, host, port):
         """ Add a second host/port to try to connected to once max number of retries has been done"""
        self.alt_host = host
        self.alt_port = port

我将此代码称为:

factory = Factory()
reactor.connectTCP(self.host, self.port, factory)
factory.addHost(self.alt_host, self.alt_port)

这不令人满意,因为我必须向工厂发送第二台服务器的地址。我正在寻找基于第二个reactor.connectTCP()调用或更好地使用扭曲机制(延迟?)的不同解决方案。

0 个答案:

没有答案