Async python Socket Server using gobject

Recently I created a small command line python utility to process some stuff on a TCP socket connection. I used the standard python SocketServer class because it was dead simple to use for my purposes.

However, as the requirements of the utility grew (a GUI), I hit the main problem with SocketServers - they block - which is not so good for GUIs.

So, instead of using nasty old threading, I worked out how to use gobject.io_add_watch() to do everything in the gobject/gtk main loop. This makes it very simple to have this run in a gtk UI without needing threads.

The basic pattern is shown below. The first function, server(), sets up the socket (bind, listen) and waits for connections, but doesn't block. Instead it sets a watch and when a new connection comes in it calls a listener(). This accepts the new connection and creates a handler(). The handler is called whenever input is available on the connection. Note that listener and handler return True (typically) so that the io_watch keeps running. After a connection is closed, the listener is called again to create a new connection.

It took me a while to work this out and I couldn't find all of this in one place on the web, so here it is. Hope it helps someone.

I hadn't seen that. Probably because I was not looking here. :) My utility is for work and I didn't want to depend on roxlib. It's also too bad that the (py)gobject handlers don't directly accept python generators as their callbacks.

P.S. it appears that <code> blocks are eating blank lines. Is there a way to fix that?