1

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

  • Possible duplicate of [Twisted: ReconnectingClientFactory connection to different servers](https://stackoverflow.com/questions/14255289/twisted-reconnectingclientfactory-connection-to-different-servers) – notorious.no Oct 03 '17 at 17:20

1 Answers1

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()
Jean-Paul Calderone
  • 47,755
  • 6
  • 94
  • 122
  • This doesn't seem to work, I run a new server in a command shell in windows at port 8001. If I close the main server running on port 8000, I see the output `Trying to reconnect` and then the client code exits. However if I manually change the port from 8000 to 8001 in the `reactor.connectTCP(...)` which is outside the `MyProtocol` class then I am able to connect to that server. So I can verify that server keeps running but I am not able to connect to it on disconnection. – Piyush Divyanakar Oct 04 '17 at 02:51
  • 1
    **SORRY! My mistake**, right after `reactor.connectTCP(...)` there was a `reactor.stop()` in `clientConnectionLost()`. This may be causing the reactor to stop before it was able to connect. **The solution works**. – Piyush Divyanakar Oct 04 '17 at 03:25