[Twisted-Python] Application mode: Killing a peer connection from the server in a thread. Is this correct?
glyph at twistedmatrix.com
Sun Mar 14 16:27:39 EDT 2010
No. (In answer to the subject.)
On Mar 14, 2010, at 1:24 AM, Jonathan Sawyer wrote:
> Now here's my problem: I want to kill connections from the server that have been idle for, say, 30 seconds. An idle connection is one in which is a _valid_ connection (i.e., it hasn't disconnected from the server) but hasn't sent any data for 30 seconds. The way I have initially set it up was in a thread.
That's your problem. You may not call Twisted APIs of any kind from a thread. That goes *double* for threads started with start_new_thread; if you start threads that way you will have problems with clean shutdown as well. If you have work you want to do in a thread in Twisted, use reactor.callInThread.
If, for some reason, you needed to tell a transport to disconnect from a thread, the right way to do it would be to call reactor.callFromThread(transport.loseConnection).
However, this is still wrong, as there's no need to spin up or manage threads in order to run timed events in Twisted.
Bottom line: don't use threads. If you think you need to in order to perform some basic task, there is probably a Twisted API you haven't learned about yet.
> Can anyone direct me on the proper way to kill a connection from the server end in a clean manner?
If you want to check the connection every 30 seconds, use a LoopingCall that calls your 'check' function every 30 seconds, to check the activity flag and call loseConnection if necessary.
You should also know that until <http://twistedmatrix.com/trac/ticket/78> is closed, your connection won't be "killed" so much as it is "shut down"; the socket will wait until all of its remaining data has been sent (or the TCP-level timeout has passed) before closing.
More information about the Twisted-Python