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.

This is a timestamp TCP client that knows how to speak to the file-like Socket Server class<br />

StreamRequestHandler objects.<br />

Lines 1021<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 while True:<br />

11 tcpCliSock = socket(AF_INET, SOCK_STREAM)<br />

12 tcpCliSock.connect(ADDR)<br />

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

14 if not data:<br />

15 break<br />

16 tcpCliSock.send('%s\r\n' % data)<br />

17 data = tcpCliSock.recv(BUFSIZ)<br />

18 if not data:<br />

19 break<br />

20 print data.strip()<br />

21 tcpCliSock.close()<br />

The default behavior of the SocketServer request handlers is to accept a connection, get the request,<br />

and close the connection. This makes it so that we cannot keep our connection throughout the execution<br />

of our application, so we need to create a new socket each time we send a message to the server.<br />

This behavior makes the TCP server act more like a UDP server; however, this can be changed by<br />

overriding the appropriate methods in our request handler classes. We leave this as an exercise at the<br />

end of this chapter.<br />

Other than the fact that our client is somewhat "inside-out" now (because we have to create a<br />

connection each time), the only other minor difference was previewed in the line-by-line explanation for<br />

the server code: the handler class we are using treats socket communication like a file, so we have to<br />

send line-termination characters (carriage return and NEWLINE) each way. The server just retains and<br />

reuses the ones we send here. When we get a message back from the server, we strip() them and just<br />

use the NEWLINE automatically provided by the print statement.<br />

16.4.3. Executing our TCP Server and Client(s)<br />

Here is the output of our SocketServer TCP client:<br />

$ tsTclntSS.py<br />

> 'Tis but a scratch.<br />

[Tue Apr 18 20:55:49 2006] 'Tis but a scratch.<br />

> Just a flesh wound.<br />

[Tue Apr 18 20:55:56 2006] Just a flesh wound.

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

Saved successfully!

Ooh no, something went wrong!