How to create a twisted factory to handle disconnects?

I have a ReconnectingClientFactory in a module. I would like the module to be as flexible as possible. I need only one TCP connection. I use factory as a persistent interface for this connection. In the past, the factory responded to disconnections by repeating the connection endlessly, never telling the top level script (the script that imports the module) that there were connection problems.

Here is a brief example of what I have:

Factory(protocol.ReconnectingClientFactory):

    def clientConnectionFailed(self, connector, reason):
        ...

    def clientConnectionLost(self, connector, reason):
        ...

I think that it is best if I tell the top level script (the script that imports the module) when there are connection problems. Thus, the top level of the script can determine the resolution behavior of the disconnect, and not all hard-coded in the module. But what is the best way to report connection problems to a top level script?

I could throw an exception, but where would he be caught? I think the reactor would catch him, but how does this help?

There are no callbacks or errors that I can run to report the top script connection problems.

The top script may provide certain functions [as arguments] to be called when connection problems occur. Is this a good design?

+5
source share
1 answer

, . , .

endpoints, ClientFactory. . ( ClientFactory.clientConnectionLost IProtocol.connectionLost, API , IProtocol, ), , clientConnectionFailed Deferred, connect. , , , , " , ", Deferred -retry-loop - , ReconnectingClientFactory:

# Warning, untested, sorry if it broken.
@inlineCallbacks
def retry(deferredThing, delay=30.0, retryCount=5):
    retries = retryCount
    while True:
        try:
            result = yield deferredThing()
        except:
            if not retries:
                raise
            retries -= 1
            log.err()
            yield deferLater(reactor, delay, lambda : None)
        else:
            returnValue(result)

, , deferredThing a Deferred, , , IStreamServerEndpoint.connect, connectionLost , , .

Deferreds .

+3

All Articles