[Twisted-Python] Need help pulling things together.

Brendon Colby brendoncolby at gmail.com
Tue May 22 15:32:02 EDT 2007


Greetings,

I've struggled to learn Twisted for a couple of years, usually hitting
the same wall I've hit yet again and giving up. I acknowledge the huge
benefit to using Twisted for what I want to do, so I wanted to see if
some nice folks out there can help me pull some things together. I've
gone through the docs, previous posts, Twisted code and examples etc.
quite extensively. Things just have not gelled for me.

The project I'm working on is, at its core, a relatively basic chat
server. There are "Areas" and "Users". What I do now with asynchat is
create a new User() object for each UserSocket() object (each user who
connects). The UserSocket() class parses the socket data and does a
getattr(), i.e. if the client sends a "sendAreaMessage" command I
getattr() User.do_sendAreaMessage(). The work is done in the User
class, then an event is sent back to the user. This is the pattern my
brain wants to use with Twisted, and I'm not sure whether or not I'm
off to a bad start. I took this from the chat server example:

class ChatProtocol(basic.LineReceiver):
    delimiter = '\n'

    def connectionMade(self):
        print "Got new client!"
        self.user = User(self)
        self.message("Welcome to chat.")

    def connectionLost(self, reason):
        print "Lost a client!"

    def lineReceived(self, line):
        data = line.split(" ")
        getattr(self.user,'do_'+data[0])(data[1:])

    def message(self, message):
        self.transport.write(message + self.delimiter)

class ChatFactory(Factory):
    protocol = ChatProtocol

class Area:
    pass # Area stuff

class User:
    def __init__(self,protocol):
        print "New user"
        self.protocol = protocol

    def do_foo(self,args):
        message = "do_foo with args: "+ ' '.join(args)
        self.protocol.transport.write(message + "\n")

application = service.Application("sserverd")
internet.TCPServer(4001, ChatFactory()).setServiceParent(application)


With all the different examples I'm having a hard time finding the
"right" way to write my server using Twisted. I thought I was on to
something reading through the IRC server protocol, but without a full
server example I got lost. Do I set up a generic handleCommand() like
interface and define each command in the protocol class (i.e.
do_sendMessage) and have callbacks that my User class
redefines/implements? Or am I on the right path?

I really appreciate any input on this!

Brendon




More information about the Twisted-Python mailing list