04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

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

CHAPTER 14 ■ NETWORK PROGRAMMING 305<br />

Forking and Threading with SocketServers<br />

Creating a forking or threading server with the SocketServer framework is so simple it hardly needs<br />

any explanation. Listings 14-4 and 14-5 show you how to make the server from Listing 14-3 forking<br />

and threading, respectively. The forking and threading behavior is, of course, only useful if the<br />

handle method takes a long time to finish. Note that forking doesn’t work in Windows.<br />

Listing 14-4. A Forking Server<br />

from SocketServer import TCPServer, ForkingMixIn, StreamRequestHandler<br />

class Server(ForkingMixIn, TCPServer): pass<br />

class Handler(StreamRequestHandler):<br />

def handle(self):<br />

addr = self.request.getpeername()<br />

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

self.wfile.write('Thank you for connecting')<br />

server = Server(('', 1234), Handler)<br />

server.serve_forever()<br />

Listing 14-5. A Threading Server<br />

from SocketServer import TCPServer, ThreadingMixIn, StreamRequestHandler<br />

class Server(ThreadingMixIn, TCPServer): pass<br />

class Handler(StreamRequestHandler):<br />

def handle(self):<br />

addr = self.request.getpeername()<br />

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

self.wfile.write('Thank you for connecting')<br />

server = Server(('', 1234), Handler)<br />

server.serve_forever()<br />

Asynchronous I/O with select and poll<br />

When a server communicates with a client, the data it receives from the client may come in fits<br />

and spurts. If you’re using forking and threading, that’s not a problem. While one parallel waits<br />

for data, other parallels may continue dealing with their own clients. Another way to go, however,<br />

is to deal only with the clients that actually have something to say at a given moment. You don’t<br />

even have to hear them out—you just hear (or, rather, read) a little bit, and then put it back in<br />

line with the others.

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

Saved successfully!

Ooh no, something went wrong!