Network programming is a delicate mix of sending messages, waiting for events and reacting. Twisted is a python library that aims to simplify this process. From their website:
Twisted is an event-driven networking engine written in Python
Pretty straight forward.
Echo Server
The first example (lifted directly from their website) is an Echo Server:
The method dataReceived which is provided by the Protocol class is called by the reactor when a network event of interest presents itself to your program.
HTTP
Out of the box, you’re also given some tools to talk web actions. Again, lifted from the twisted website is an example web server:
It’s a pretty brute-force way to deal with assembling a web server, but it’ll get the job done. The render_GET method of the Resource derived Counter class will perform all of the work when a GET request is received by the server.
Chat Server
I’ll finish up with some original content here, that is a PubSub example (which twisted website has an example of).
Getting a leg up using the LineReceiver protocol as a base, really simplifies our implementation. This allows us little gems like connectionMade, connectionLost and lineReceived . . all pieces that you’d expect in a chat server:
We use a really crude regular expression with some basic captures to pull apart the instruction sent by the client:
When receiving a line, we can respond back to the client; or we can broadcast to the portfolio of connections:
The only part left out here, is the broadcast method. Which is simply a for-loop: