[Twisted-Python] Connecting to multiple servers
Antonio Beamud Montero
antonio.beamud at gmail.com
Wed Jul 8 08:33:07 MDT 2009
Gerrat Rickert escribió:
>> Ok, but when I use reactor.connectTCP no deferred is returned.. How I
>> can stop the reactor when all connections has finished?
>>
>> Thanks.
>>
>
> ...it would be helpful if you provided an actual example
> (your example did not use a "reactor.connectTCP");
> but in general terms, if you're connecting to multiple servers
> and want to wait till all connections are finished, you'll need to
> track the connections, and call reactor.stop() once the last
> connection is closed.
>
Well, finally I solved the problem next way:
I've created a factory that inherits from ReconnectingClientFactory. In
the __init__, I've created a deferred:
def __init__(self):
self.deferred = defer.Deferred()
If all goes ok, then self.deferred.callback('ok'), else
(clientConnectionLost, etc) self.deferred.errback(reason).
When I create the factory to pass it to reactor.connectTCP, I save the
deferred in a list:
dlist = []
myf = MyFactory(args)
reactor.connectTCP(host, port, myf)
myf.deferred.addCallback(lambda _: None)
myf.deferred.addErrback(lambda _:None)
dlist.append(myf.deferred)
...
flist = defer.DeferredList(dlist)
flist.addCallback(lambda _: reactor.stop())
flist.addErrback(lambda _: reactor.stop())
reactor.run()
I think it's the best way, only when all connections have finished the
reactor is stopped.
Greetings.
More information about the Twisted-Python
mailing list