2013-12-20 114 views
1

我正在写Twisted框架的tcp代理并需要一个简单的客户端故障转移。如果代理无法连接到一个后端,则连接到列表中的下一个。我用 reactor.connectTCP(host, port, factory)代理,直到我来到这个任务,但它不吐出错误,如果它不能连接。我该如何捕获,它无法连接并尝试其他主机,或者我应该使用其他连接方法?蟒蛇扭曲的客户端连接故障转移

+0

对不起,终于找到答案了:http://stackoverflow.com/questions/14255289/twisted-reconnectingclientfactory-connection-to-different-servers –

回答

0

可以使用推迟这样做,如果第一个失败

class MyClientFactory(ClientFactory): 

    protocol = ClientProtocol 

    def __init__(self, request): 
     self.request = request 
     self.deferred = defer.Deferred() 

    def handleReply(self, command, reply): 
     # Handle the reply 
     self.deferred.callback(0) 

    def clientConnectionFailed(self, connector, reason): 
     self.deferred.errback(reason) 

def send(_, host, port, msg): 
    factory = MyClientFactory(msg) 
    reactor.connectTCP(host, port, factory) 
    return factory.deferred 

d = Deferred() 
d.addErrback(send, host1, port1, msg1) 
d.addErrback(send, host2, port2, msg2) 
# ... 
d.addBoth(lambda _: print "finished") 

这将触发下一个errback可,否则后藤打印功能。