Python Twisted Stopping The Reactor With Multiple Clients

拥有回忆 提交于 2019-12-13 06:26:14

问题


If I create multiple clients by doing this:

def main():
    clients = [None]*10

    for i in range(0, 10):
        clients[i] = ClientFactory()
        reactor.connectTCP('192.168.0.1', 8000, clients[i])

    reactor.run()

How to I -gracefully- stop the reactor? If I do:

self.transport.loseconnection()

In the protocol, then do:

reactor.stop()

In the factory, then the next client is going to try to come along a stop the reactor again. However, this of course leads to the error:

Can't stop a reactor that isn't running

How can I gracefully stop the reactor in such a scenario?


回答1:


Take your reactor-management code out of your protocol implementation. Replace it with some event-notification code that you can use to learn when the connection has done everything it needs to do. For example, fire a Deferred.

Then wait on all the deferreds and stop the reactor when they're all done. You might find gatherResults helpful for this.




回答2:


It's been a while since I did anything with Twisted, but couldn't you just check the value of the reactor.running property first? E.g.,

# Gracefully stop the reactor
if reactor.running:
    reactor.stop()


来源:https://stackoverflow.com/questions/17288676/python-twisted-stopping-the-reactor-with-multiple-clients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!