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.

One way to create this "friendly" exit is to put the server's while loop<br />

inside the except clause of a TRy-except statement and monitor for<br />

EOFError or KeyboardInterrupt exceptions. Then in the except clause,<br />

you can make a call to close the server's socket.<br />

The interesting thing about this simple networked application is that we are not only showing how our<br />

data take a round trip from the client to the server and back to the client, but we also use the server as<br />

a sort of "time server," because the timestamp we receive is purely from the server.<br />

16.3.6. Creating a UDP Server<br />

UDP servers do not require as much setup as TCP servers because they are not connection-oriented.<br />

There is virtually no work that needs to be done other than just waiting for incoming connections.<br />

ss = socket() # create server socket<br />

ss.bind() # bind server socket<br />

inf_loop: # server infinite loop<br />

cs = ss.recvfrom()/ss.sendto()# dialog (receive/send)<br />

ss.close() # close server socket<br />

As you can see from the pseudocode, there is nothing extra other than the usual create-the-socket and<br />

bind it to the local address (host/port pair). The infinite loop consists of receiving a message from a<br />

client, returning a timestamped one, then going back to wait for another message. Again, the close()<br />

call is optional and will not be reached due to the infinite loop, but it serves as a reminder that it should<br />

be part of the graceful or intelligent exit scheme we've been mentioning.<br />

One other significant different between UDP and TCP servers is that because datagram sockets are<br />

connectionless, there is no "handing off" of a client connection to a separate socket for succeeding<br />

communication. These servers just accept messages and perhaps reply.<br />

You will find the code to tsUserv.py in Example 16.3, a UDP version of the TCP server seen earlier. It<br />

accepts a client message and returns it to the client timestamped.<br />

Example 16.3. UDP Timestamp Server (tsUserv.py)

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

Saved successfully!

Ooh no, something went wrong!