2013-12-20 154 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可,否則後藤打印功能。