15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

16.5. *Introduction to the Twisted Framework<br />

Twisted is a complete event-driven networking framework that allows you to both use and develop<br />

complete asynchronous networked applications and protocols. It is not part of the <strong>Python</strong> Standard<br />

library at the time of writing and must be downloaded and installed separately (see link at the end of the<br />

chapter). It provides a significant amount of support for you to build complete systems with: network<br />

protocols, threading, security and authentication, chat/IM, DBM and RDBMS database integration, Web/<br />

Internet, e-mail, command-line arguments, GUI toolkit integration, etc.<br />

Using Twisted to implement our tiny simplistic example is like using a sledgehammer to pound a<br />

thumbtack, but you have to get started somehow, and our application is the equivalent to the "hello<br />

world" of networked applications.<br />

Like SocketServer, most of the functionality of Twisted lies in its classes. In particular for our examples,<br />

we will be using the classes found in the reactor and protocol subpackages of Twisted's Internet<br />

component.<br />

16.5.1. Creating a Twisted Reactor TCP Server<br />

You will find our code similar to that of the SocketServer example. Instead of a handler class, we create<br />

a protocol class and override several methods in the same manner as installing callbacks. Also, this<br />

example is asynchronous. Let us take a look at the server now.<br />

Line-by-Line Explanation<br />

Lines 16<br />

The setup lines of code include the usual module imports, most notably the protocol and reactor<br />

subpackages of twisted.internet and our constant port number.<br />

Lines 814<br />

We derive the Protocol class and call ours TSServProtocol for our timestamp server. We then override<br />

connectionMade(), a method that is executed when a client connects to us, and dataReceived(), called<br />

when a client sends a piece of data across the network. The reactor passes in the data as an argument<br />

to this method so we can get access to it right away without having to extract it ourselves.<br />

Example 16.7. Twisted Reactor Timestamp TCP Server (tsTservTW.py)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!