Starting and stopping Twisted connections

360 views Asked by At

I'm writing application that uses python Twisted API (namely WebSocketClientProtocol, WebSocketClientFactory, ReconnectiongClientFactory. I want to wrap client factory into reader with following interface

class Reader: 
    def start(self):
        pass
    def stop(self):
        pass

Start function will be used to open connection (i.e. connect on ws api and start reading data), while stop will stop such connection.

My issue is that if I use reactor.run() inside start, connection starts and everything is OK, but my code never goes pass that line (looks like blocking call to me) and I cannot execute subsequent lines (include .stop in my tests).

I have tried using variants such as reactor.callFromThread(reactor.run) and reactor.callFromThread(reactor.stop) or even excplicity calling Thread(target=...) but none seems to work (they usually don't build protocol or open connection at all).

Any help or guidelines on how to implement Reader.start and Reader.stop are welcome.

1

There are 1 answers

3
Jean-Paul Calderone On BEST ANSWER

If you put reactor.run inside Reader.start then Reader will be a difficult component to use alongside other code. Your difficulties are just the first symptom of this.

Calling reactor.run and reactor.stop are the job of code responsible for managing the lifetime of your application. Put those calls somewhere separate from your WebSocket application code. For example:

r = Reader()
r.start()
reactor.run()

Or better yet, implement a twist(d) plugin and let twist(d) manage the reactor for you.