04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

308 CHAPTER 14 ■ NETWORK PROGRAMMING<br />

s.listen(5)<br />

p = select.poll()<br />

p.register(s)<br />

while True:<br />

events = p.poll()<br />

for fd, event in events:<br />

if fdmap[fd] is s:<br />

c, addr = s.accept()<br />

print 'Got connection from', addr<br />

p.register(c)<br />

fdmap[c.fileno()] = c<br />

elif event & select.POLLIN:<br />

data = fdmap[fd].recv(1024)<br />

if not data: # No data -- connection closed<br />

print fdmap[fd].getpeername(), 'disconnected'<br />

p.unregister(fd)<br />

del fdmap[fd]<br />

else:<br />

print data<br />

More Information<br />

You can find more information about select and poll in the Python Standard Library Reference<br />

(http://python.org/doc/lib/module-select.html). Also, reading the source code of the standard<br />

library modules asyncore and asynchat (found in the asyncore.py and asynchat.py files in<br />

your Python installation) can be enlightening.<br />

Twisted<br />

Twisted, from Twisted Matrix Laboratories (http://twistedmatrix.com), is an event-driven<br />

networking framework for Python, originally developed for network games but now used by all<br />

kinds of network software. In Twisted, you implement event handlers, much like you would in<br />

a GUI toolkit (see Chapter 12). In fact, Twisted works quite nicely together with several common<br />

GUI toolkits (Tk, GTK, Qt, and wxWidgets). The Twisted documentation may not always be<br />

easy to navigate (although it’s continuously improving), but there is much information to be<br />

found on the Twisted Matrix Web site, twistedmatrix.com. In this section, I’ll cover some of the<br />

basic concepts and show you how to do some relatively simple network programming using<br />

Twisted. Once you grasp the basic concepts, you can check out the Twisted documentation to<br />

do some more serious network programming. Twisted is a very rich framework and supports,<br />

among other things, Web servers and clients, SSH2, SMTP, POP3, IMAP4, AIM, ICQ, IRC, MSN,<br />

Jabber, NNTP, DNS, and more!<br />

Downloading and Installing Twisted<br />

Installing Twisted is quite easy. First, go to the Twisted Matrix Web page (http://<br />

twistedmatrix.com) and, from there, follow the link to the download page. If you’re using<br />

Windows, download the Windows installer for your version of Python; if you’re using some

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

Saved successfully!

Ooh no, something went wrong!