09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

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

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

CHAPTER 7 ■ SERVER ARCHITECTURE<br />

5. Once this server has finished transmitting the answer, we tell the poll object to<br />

swap the client socket back over to being listened to for new incoming data.<br />

6. After many question-answer exchanges, the client will finally close the<br />

connection. Oddly enough, the POLLHUP, POLLERR, and POLLNVAL circumstances<br />

that poll() can tell us about—all <strong>of</strong> which indicate that the connection has<br />

closed one way or another—are returned only if we are trying to write to the<br />

socket, not read from it. So when an attempt to read returns zero bytes, we have<br />

to tell the poll object that we now want to write to the socket so that we receive<br />

the <strong>of</strong>ficial notification that the connection is closed.<br />

The performance <strong>of</strong> this vastly improved server design is shown in Figure 7–2. By the time its<br />

throughput begins to really degrade, it has achieved twice the requests per second <strong>of</strong> the simple server<br />

with which we started the chapter.<br />

Figure 7–2. Polling server benchmark<br />

Of course, this factor-<strong>of</strong>-two improvement is very specific to the design <strong>of</strong> this server and the<br />

particular memory and processor layout <strong>of</strong> my laptop. Depending on the length and cost <strong>of</strong> client<br />

requests, other network services could see much more or much less improvement than our Launcelot<br />

service has displayed here. But you can see that a pure event-driven design like this one turns the focus<br />

<strong>of</strong> your program away from the question <strong>of</strong> what one particular client will want next, and toward the<br />

question <strong>of</strong> what event is ready to happen regardless <strong>of</strong> where it comes from.<br />

Poll vs. Select<br />

A slightly older mechanism for writing event-driven servers that listen to sockets is to use the select()<br />

call, which like poll() is available from the <strong>Python</strong> select module in the Standard Library. I chose to use<br />

112

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

Saved successfully!

Ooh no, something went wrong!