[Twisted-Python] using a reactor in a loop

Johann Borck johann.borck at densedata.com
Thu Mar 1 17:05:55 EST 2007

Tom Brown wrote:
> My goal is this:
> 1) do specific tasks
> 2) run the server and wait for a connection
> 3) when a connection is made, do tasks as instructed by the client in the 
> AqapProtocol code.
> 4) when connection is lost, close server and go back to 1)
> Shutting down the server is not necessary if I could get past the 
> reactor.run(). A previous post suggested I use deferreds. So, that is 
> probably what I need to. I just need to learn how to use them.

There's really good documentation about twisted and its event-driven 
programming model, there you'll find what you're looking for. in twisted 
you never "get past" the reactor.run() (until you quit the application), 
everything is done inside its loop. so when using twisted you should 
rather consider this:

1) run the event-loop
2) do specific tasks (if you need to complete long running tasks, you could use deferToThread or a pool of threads, to keep your event-loop responsive ) 
3) setup listener for connections (now you have your server)
4) when a connection is made, do tasks as instructed by the client in the 
AqapProtocol code.
5) if really necessary, stop listening for/refuse connections without stopping the eventloop, but maybe it's better to return a "service suspended, come back later" kind of message
6) goto 2) 

AFAIK twisted doesn't support restarting the reactor, there're some issues with cleaning up the state. But when you get used to it, you'll never feel the need to do that anyway, which might be the main reason why it's neither supported nor really discussed. You can do anything you want while the reactor is running. 


> Thanks,
> Tom
> _______________________________________________
> Twisted-Python mailing list
> Twisted-Python at twistedmatrix.com
> http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

More information about the Twisted-Python mailing list