[Twisted-Python] [Twisted-web] Telnet chat server

glyph at divmod.com glyph at divmod.com
Thu Jun 4 00:51:10 EDT 2009

This message is more appropriate for the twisted-python list, as it has 
nothing to do with "web", so I've cross-posted it there.

On 3 Jun, 10:57 pm, woahyeahyeah at yahoo.com wrote:
>I've got a simple little chat server set up that people can telnet 
>into.  The code is as follows:

>from twisted.internet import reactor
>from twisted.internet.protocol import ServerFactory
>from twisted.protocols.basic import LineOnlyReceiver
>import threading

^ This is where things start to go (horribly) wrong.

The protocol looks basically correct, but this part:
>def Test():
>    global test
>    factory.sendMessageToAllClients('Hey.')
>    test = threading.Timer(1.0,
>    test.start()
>test = threading.Timer(1.0, Test)

is very, very wrong.  You cannot call Twisted APIs from a thread.  Ever. 
This is very important :).  The behavior to you appeared to be some 
strange timing issues, but you can get anything from corrupted data to 
crashing the entire program.
>Is there any way to get this to send the message and have it show up 
>for a client even when they're idle?

Yes.  Use the reactor's timed-event APIs rather than threads.  In other 
words, do this, after you create your factory:

    from twisted.internet.task import LoopingCall
    LoopingCall(factory.sendMessageToAllClients, 'Hey.').start(1.0)

You may be interested to also read about these APIs:



More information about the Twisted-Python mailing list