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.

it can immediately make a connection to a server by using the socket's connect() method. When the<br />

connection has been established, then it can participate in a dialog with the server. Once the client has<br />

completed its transaction, it may close its socket, terminating the connection.<br />

We present the code for tsTclnt.py in Example 16.2; it connects to the server and prompts the user for<br />

line after line of data. The server returns this data timestamped, which is presented to the user by the<br />

client code.<br />

Example 16.2. TCP Timestamp Client (tsTclnt.py)<br />

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

back with a timestamp prefix, and displays the results 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 tcpCliSock = socket(AF_INET, SOCK_STREAM)<br />

11 tcpCliSock.connect(ADDR)<br />

12<br />

13 while True:<br />

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

15 if not data:<br />

16 break<br />

17 tcpCliSock.send(data)<br />

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

19 if not data:<br />

20 break<br />

21 print data<br />

22<br />

23 tcpCliSock.close()<br />

Line-by-Line Explanation<br />

Lines 13<br />

After the Unix startup line, we import all the attributes from the socket module.<br />

Lines 511<br />

The HOST and PORT variables refer to the server's hostname and port number. Since we are running our<br />

test (in this case) on the same machine, HOST contains the local hostname (change it accordingly if you<br />

are running your server on a different host). The port number PORT should be exactly the same as what<br />

you set for your server (otherwise there won't be much communication[!]). We also choose the same<br />

buffer size, 1K.

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

Saved successfully!

Ooh no, something went wrong!