15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

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

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

cs = socket() # create client socket<br />

comm_loop: # communication loop<br />

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

cs.close() # close client socket<br />

Once a socket object is created, we enter the dialog loop of exchanging messages with the server. When<br />

communication is complete, the socket is closed.<br />

The real client code, tsUclnt.py, is presented in Example 16.4.<br />

Example 16.4. UDP Timestamp Client (tsUclnt.py)<br />

Creates a UDP client that prompts the user for messages to send to the server, gets them<br />

back with a timestamp prefix, and displays them back to the user.<br />

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

2<br />

3 from socket import *<br />

4<br />

5 HOST = 'localhost'<br />

6 PORT = 21567<br />

7 BUFSIZ = 1024<br />

8 ADDR = (HOST, PORT)<br />

9<br />

10 udpCliSock = socket(AF_INET, SOCK_DGRAM)<br />

11<br />

12 while True:<br />

13 data = raw_input('> ')<br />

14 if not data:<br />

15 break<br />

16 udpCliSock.sendto(data, ADDR)<br />

17 data, ADDR = udpCliSock.recvfrom(BUFSIZ)<br />

18 if not data:<br />

19 break<br />

20 print dataudpCliSock.close()<br />

21<br />

22 udpCliSock.close()<br />

Line-by-Line Explanation<br />

Lines 13<br />

After the Unix startup line, we import all the attributes from the socket module, again, just like in the<br />

TCP version of the client.<br />

Lines 510<br />

Because we are running the server on our local machine again, we use "localhost" and the same port<br />

number on the client side, not to mention the same 1K buffer. We allocate our socket object in the same

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

Saved successfully!

Ooh no, something went wrong!