twisted and comet (comet in 60 seconds)

September 19, 2009

I’ve been looking into twisted to build a comet based app. It’s not a hard task, given that you can tune a lot of parameters (including which kind of reactor), but the basics are very interesting. Combining this approach along with a nginx based architecture has given me excellent results.

Before reading my example, I have to say that I’m inspired by this post, which shows how easy is to start with twisted (dont get me wrong, but it can get pretty hairy from there, specially with tasks and deferred). I suggest you read that first to relate to my source code, as I don’t have the same teaching skills as the author of that post.

The most important part here is that you may return server.NOT_DONE_YET from the render_GET method, so the connection keeps open. The task loop is not the best option, but it serves well to send some data to the comet connection.

from twisted.internet import reactor, task
from twisted.web.server import Site
from twisted.web import server
from twisted.web.resource import Resource
import time

class ClockPage(Resource):
isLeaf = True
def __init__(self):
loopingCall = task.LoopingCall(self.__print_time)
loopingCall.start(1, False)

def render_GET(self, request):
request.write('<b>%s</b>' % (time.ctime(),))
return server.NOT_DONE_YET

def __print_time(self):
for p in self.presence:
p.write('<b>%s</b>' % (time.ctime(),))

resource = ClockPage()
factory = Site(resource)
reactor.listenTCP(8080, factory)

The wordpress sourcecode highlight may mangle the html tags insite the prints, so check it before running the example.

That’s it. Thanks to Ivan (irr) who sent the original post and fiorix for the heads up to twisted last week.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: