09.11.2016 Views

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

Create successful ePaper yourself

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

CHAPTER 2 ■ UDP<br />

Unreliability, Back<strong>of</strong>f, Blocking, Timeouts<br />

Because the client and server in the previous section were both running on the same machine and<br />

talking through its loopback interface—which is not even a physical network card that could experience<br />

a signaling glitch and lose a packet, but merely a virtual connection back to the same machine deep in<br />

the network stack—there was no real way that packets could get lost, and so we did not actually see any<br />

<strong>of</strong> the inconvenience <strong>of</strong> UDP. How does code change when packets could really be lost?<br />

Take a look at Listing 2–2. Unlike the previous example, you can run this client and server on two<br />

different machines on the Internet. And instead <strong>of</strong> always answering client requests, this server<br />

randomly chooses to answer only half <strong>of</strong> the requests coming in from clients—which will let us<br />

demonstrate how to build reliability into our client code, without waiting what might be hours for a real<br />

dropped packet to occur!<br />

Listing 2–2. UDP Server and Client on Different Machines<br />

#!/usr/bin/env python<br />

# <strong>Foundations</strong> <strong>of</strong> <strong>Python</strong> <strong>Network</strong> <strong>Programming</strong> - Chapter 2 - udp_remote.py<br />

# UDP client and server for talking over the network<br />

import random, socket, sys<br />

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)<br />

MAX = 65535<br />

PORT = 1060<br />

if 2 2.0:<br />

22

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

Saved successfully!

Ooh no, something went wrong!