[Twisted-Python] client connecting to 2 servers (non simultaneously)
benjamin.bertrand at lfv.se
benjamin.bertrand at lfv.se
Tue Jan 11 05:17:58 EST 2011
Hi,
I'm new to twisted and I have started to write a new protocol with a TCP
client and server.
In my protocol, a client should be able to connect to 2 servers
(master/slave node - only the master accepts connection).
The client should try to connect to server1. If it fails, try to connect
to server2 (after a specific timeout). If that fails, try server1...
I came up with a solution (see below).
As I'm new to twisted and I haven't seen anything like that in the
examples, I'd like to check if that's a proper way to do it.
Any comments is welcome.
Thanks
Benjamin
***********************************************
class MyClientFactory(ClientFactory):
protocol = MyClientProtocol
def __init__(self, host2=None):
self.host1 = None
self.host2 = host2
def clientConnectionFailed(self, connector, reason):
from twisted.internet import reactor
if self.host2 is None:
# host2 is not defined, reconnect to host1
reactor.callLater(2.0, connector.connect)
else:
destination = connector.getDestination()
if self.host1 is None:
# First connection failed, initialize host1, and try
host2
self.host1 = destination.host
host = self.host2
elif destination.host == self.host1:
# Connection to host1 failed, try host2
host = self.host2
else:
# Connection to host2 failed, try host1
host = self.host1
reactor.callLater(2.0, reactor.connectTCP, host,
destination.port, self)
factory = MyClientFactory(server2)
from twisted.internet import reactor
reactor.connectTCP(server1, 8010, factory)
reactor.run()
***********************************************
More information about the Twisted-Python
mailing list