Reconnect to different address in twisted?

2019-08-23 01:54发布

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条回答
We Are One
2楼-- · 2019-08-23 02:16
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()
查看更多
登录 后发表回答