问题
I have a server that sends my client the address of a backup server in case it goes down. On the server side the backup server is running. On the client side once the connection is lost I am not able to make the client to connect to the backup server. I know that I have to add the connection logic to the following callback in twisted.internet.protcol.Protocol
class MyProtocol(Protocol):
def connectionLost(self, reason):
print 'Connection Lost'
print 'Trying to reconnect'
# How do I reconnect to another address say at localhost:8001
f = Factory()
f.protocol = MyProtocol
reactor.connectTCP("localhost", 8000, f)
reactor.run()
If the server on localhost:8000
stopped it will trigger the connectionLost(..)
method. In this method I want to put the logic to connect to the backup host which in this case is say localhost:8001
, but could be anything arbitrary. How do I do
this?
Edit: I want to do this without using ReconnectingClientFactory
回答1:
class MyProtocol(Protocol):
def connectionLost(self, reason):
print 'Connection Lost'
print 'Trying to reconnect'
reactor.connectTCP(
"localhost", 8001, Factory.forProtocol(MyProtocol),
)
reactor.connectTCP("localhost", 8000, Factory.forProtocol(MyProtocol))
reactor.run()
来源:https://stackoverflow.com/questions/46538287/reconnect-to-different-address-in-twisted