[Twisted-Python] Automatic reconnection
Andrew Bennetts
andrew-twisted at puzzling.org
Mon Mar 11 18:54:59 MST 2002
Hi all,
I need a tcp.Client that can automatically reconnect when disconnected.
I've written the following class, and it seems to work, but...
* It doesn't handle unix sockets (that's ok for me, I'm using Windows, so I
never had them in the first place)
* I'm not sure what the "connector" is, and thus I suspect it won't for
Clients that use it.
* It's only lightly tested
Is there a better way to do this (i.e. is there a way to do this already in
Twisted, and I just haven't found it yet)?
Otherwise, I'd be interested in knowing if anyone else would find this useful,
or if maybe it should be included in Twisted. I suspect I'm not the only
person who wants to be able to write a server which automatically tries to
recover from "upstream" problems.
-Andrew.
Code:
class ReconnectingClient(tcp.Client):
"""A tcp.Client that automatically reconnects when disconnected
Overrideable attributes:
* reconnectionDelay -- number of seconds to wait before reconnecting
* maxReconnects -- maximum number of reconnects before giving up. The
reconnection counter is reset after a successfull reconnection. Set
this to None to keep retrying indefinitely.
The protocol will have connectionLost called as normal when disconnected,
but may get reconnected after that -- so if you need to reset anything in
your protocol after a disconnection, do it in Protocol.connectionLost.
"""
reconnectionDelay = 3.0
maxReconnects = 5
def __init__(self, host, port, protocol, timeout=None, connector=None):
tcp.Client.__init__(self, host, port, protocol, timeout, connector)
self.reconnectAttempts = 0
self.reconnectProtocol = protocol
def connectionLost(self):
# Disconnect as normal
tcp.Client.connectionLost(self)
# Then schedule a reconnect
if main.running: # FIXME: Is this test necessary?
print 'Lost connection, reconnecting...'
main.addTimeout(self.reconnect, self.reconnectionDelay)
def reconnect(self):
if not self.connected:
if (self.maxReconnects is None or
self.reconnectAttempts < self.maxReconnects):
self.reconnectAttempts += 1
tcp.Connection.__init__(self, self.createInternetSocket(),
self.reconnectProtocol)
self.doConnect()
main.addTimeout(self.reconnect, self.reconnectionDelay)
else:
print 'Reconnection failed after %d attempts. Giving up.' \
% (self.reconnectAttempts,)
else:
# Reset the reconnect counter if we're connected.
self.reconnectAttempts = 0
More information about the Twisted-Python
mailing list