|I l@ve RuBoard|
10.3 Socket Programming
Now that we've seen how sockets figure into the Internet picture, let's move on to explore the tools that Python provides for programming sockets with Python scripts. This section shows you how to use the Python socket interface to perform low-level network communications; in later chapters, we will instead use one of the higher-level protocol modules that hide underlying sockets.
The basic socket interface in Python is the standard library's socket module. Like the os POSIX module, Python's socket module is just a thin wrapper (interface layer) over the underlying C library's socket calls. Like Python files, it's also object-based: methods of a socket object implemented by this module call out to the corresponding C library's operations after data conversions. The socket module also includes tools for converting bytes to a standard network ordering, wrapping socket objects in simple file objects, and more. It supports socket programming on any machine that supports BSD-style sockets -- MS Windows, Linux, Unix, etc. -- and so provides a portable socket interface.
10.3.1 Socket Basics
To create a connection between machines, Python programs import the socket module, create a socket object, and call the object's methods to establish connections and send and receive data. Socket object methods map directly to socket calls in the C library. For example, the script in Example 10-1 implements a program that simply listens for a connection on a socket, and echoes back over a socket whatever it receives through that socket, adding 'Echo=>' string prefixes.
######################################################### # Server side: open a socket on a port, listen for # a message from a client, and send an echo reply; # this is a simple one-shot listen/reply per client, # but it goes into an infinite loop to listen for # more clients as long as this server script runs; ######################################################### from socket import * # get socket constructor and constants myHost = '' # server machine, '' means local host myPort = 50007 # listen on a non-reserved port number sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP socket object sockobj.bind((myHost, myPort)) # bind it to server port number sockobj.listen(5) # listen, allow 5 pending connects while 1: # listen until process killed connection, address = sockobj.accept() # wait for next client connect print 'Server connected by', address # connection is a new socket while 1: data = connection.recv(1024) # read next line on client socket if not data: break # send a reply line to the client connection.send('Echo=>' + data) # until eof when socket closed connection.close()
As mentioned earlier, we usually call programs like this that listen for incoming connections servers because they provide a service that can be accessed at a given machine and port on the Internet. Programs that connect to such a server to access its service are generally called clients. Example 10-2 shows a simple client implemented in Python.
############################################################# # Client side: use sockets to send data to the server, and # print server's reply to each message line; 'localhost' # means that the server is running on the same machine as # the client, which lets us test client and server on one # machine; to test over the Internet, run a server on a remote # machine, and set serverHost or argv to machine's domain # name or IP addr; Python sockets are a portable BSD socket # interface, with object methods for standard socket calls; ############################################################# import sys from socket import * # portable socket interface plus constants serverHost = 'localhost' # server name, or: 'starship.python.net' serverPort = 50007 # non-reserved port used by the server message = ['Hello network world'] # default text to send to server if len(sys.argv) > 1: serverHost = sys.argv # or server from cmd line arg 1 if len(sys.argv) > 2: # or text from cmd line args 2..n message = sys.argv[2:] # one message for each arg listed sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP/IP socket object sockobj.connect((serverHost, serverPort)) # connect to server machine and port for line in message: sockobj.send(line) # send line to server over socket data = sockobj.recv(1024) # receive line from server: up to 1k print 'Client received:', `data` sockobj.close() # close socket to send eof to server
10.3.1.1 Server socket calls
Before we see these programs in action, let's take a minute to explain how this client and server do their stuff. Both are fairly simple examples of socket scripts, but they illustrate common call patterns of most socket-based programs. In fact, this is boilerplate code: most socket programs generally make the same socket calls that our two scripts do, so let's step through the important points of these scripts line by line.
Programs such as Example 10-1 that provide services for other programs with sockets generally start out by following this sequence of calls:
At this point, the server is ready to accept connection requests from client programs running on remote machines (or the same machine), and falls into an infinite loop waiting for them to arrive:
Once we have a client connection, we fall into another loop to receive data from the client in blocks of 1024 bytes at a time, and echo each block back to the client:
10.3.1.2 Client socket calls
On the other hand, client programs like the one shown in Example 10-2 follow simpler call sequences. The main thing to keep in mind is that the client and server must specify the same port number when opening their sockets, and the client must identify the machine on which the server is running (in our scripts, server and client agree to use port number 50007 for their conversation, outside the standard protocol range):
And that's it. The server exchanges one or more lines of text with each client that connects. The operating system takes care of locating remote machines, routing bytes sent between programs across the Internet, and (with TCP) making sure that our messages arrive intact. That involves a lot of processing, too -- our strings may ultimately travel around the world, crossing phone wires, satellite links, and more along the way. But we can be happily ignorant of what goes on beneath the socket call layer when programming in Python.
10.3.1.3 Running socket programs locally
Okay, let's put this client and server to work. There are two ways to run these scripts -- either on the same machine or on two different machines. To run the client and the server on the same machine, bring up two command-line consoles on your computer, start the server program in one, and run the client repeatedly in the other. The server keeps running and responds to requests made each time you run the client script in the other window.
For instance, here is the text that shows up in the MS-DOS console window where I've started the server script:
C:\...\PP2E\Internet\Sockets>python echo-server.py Server connected by ('127.0.0.1', 1025) Server connected by ('127.0.0.1', 1026) Server connected by ('127.0.0.1', 1027)
The output here gives the address (machine IP name and port number) of each connecting client. Like most servers, this one runs perpetually, listening for client connection requests. This one receives three, but I have to show you the client window's text for you to understand what this means:
C:\...\PP2E\Internet\Sockets>python echo-client.py Client received: 'Echo=>Hello network world' C:\...\PP2E\Internet\Sockets>python echo-client.py localhost spam Spam SPAM Client received: 'Echo=>spam' Client received: 'Echo=>Spam' Client received: 'Echo=>SPAM' C:\...\PP2E\Internet\Sockets>python echo-client.py localhost Shrubbery Client received: 'Echo=>Shrubbery'
Here, I ran the client script three times, while the server script kept running in the other window. Each client connected to the server, sent it a message of one or more lines of text, and read back the server's reply -- an echo of each line of text sent from the client. And each time a client is run, a new connection message shows up in the server's window (that's why we got three).
It's important to notice that clients and server are running on the same machine here (a Windows PC). The server and client agree on port number, but use machine names "" and "localhost" respectively, to refer to the computer that they are running on. In fact, there is no Internet connection to speak of. Sockets also work well as cross-program communications tools on a single machine.
10.3.1.4 Running socket programs remotely
To make these scripts talk over the Internet instead of on a single machine, we have to do some extra work to run the server on a different computer. First, upload the server's source file to a remote machine where you have an account and a Python. Here's how I do it with FTP; your server name and upload interface details may vary, and there are other ways to copy files to a computer (e.g., email, web-page post forms, etc.):
C:\...\PP2E\Internet\Sockets>ftp starship.python.net Connected to starship.python.net. User (starship.python.net:(none)): lutz 331 Password required for lutz. Password: 230 User lutz logged in. ftp> put echo-server.py 200 PORT command successful. 150 Opening ASCII mode data connection for echo-server.py. 226 Transfer complete. ftp: 1322 bytes sent in 0.06Seconds 22.03Kbytes/sec. ftp> quit
Once you have the server program loaded on the other computer, you need to run it there. Connect to that computer and start the server program. I usually telnet into my server machine and start the server program as a perpetually running process from the command line. The & syntax in Unix/Linux shells can be used to run the server script in the background; we could also make the server directly executable with a #! line and a chmod command (see Chapter 2, for details). Here is the text that shows up in a Window on my PC that is running a Telnet session connected to the Linux server where I have an account (less a few deleted informational lines):
C:\...\PP2E\Internet\Sockets>telnet starship.python.net Red Hat Linux release 6.2 (Zoot) Kernel 2.2.14-5.0smp on a 2-processor i686 login: lutz Password: [lutz@starship lutz]$ python echo-server.py &  4098
Now that the server is listening for connections on the Net, run the client on your local computer multiple times again. This time, the client runs on a different machine than the server, so we pass in the server's domain or IP name as a client command-line argument. The server still uses a machine name of "" because it always listens on whatever machine it runs upon. Here is what shows up in the server's Telnet window:
[lutz@starship lutz]$ Server connected by ('22.214.171.124', 1037) Server connected by ('126.96.36.199', 1040) Server connected by ('188.8.131.52', 1043) Server connected by ('184.108.40.206', 1050)
And here is what appears in the MS-DOS console box where I run the client. A "connected by" message appears in the server Telnet window each time the client script is run in the client window:
C:\...\PP2E\Internet\Sockets>python echo-client.py starship.python.net Client received: 'Echo=>Hello network world' C:\...\PP2E\Internet\Sockets>python echo-client.py starship.python.net ni Ni NI Client received: 'Echo=>ni' Client received: 'Echo=>Ni' Client received: 'Echo=>NI' C:\...\PP2E\Internet\Sockets>python echo-client.py starship.python.net Shrubbery Client received: 'Echo=>Shrubbery' C:\...\PP2E\Internet\Sockets>ping starship.python.net Pinging starship.python.net [220.127.116.11] with 32 bytes of data: Reply from 18.104.22.168: bytes=32 time=311ms TTL=246 ctrl-C C:\...\PP2E\Internet\Sockets>python echo-client.py 22.214.171.124 Does she? Client received: 'Echo=>Does' Client received: 'Echo=>she?'
The "ping" command can be used to get an IP address for a machine's domain name; either machine name form can be used to connect in the client. This output is perhaps a bit understated -- a lot is happening under the hood. The client, running on my Windows laptop, connects with and talks to the server program running on a Linux machine perhaps thousands of miles away. It all happens about as fast as when client and server both run on the laptop, and it uses the same library calls; only the server name passed to clients differs.
10.3.1.5 Socket pragmatics
Before we move on, there are three practical usage details you should know. First of all, you can run the client and server like this on any two Internet-aware machines where Python is installed. Of course, to run clients and server on different computers, you need both a live Internet connection and access to another machine on which to run the server. You don't need a big, expensive Internet link, though -- a simple modem and dialup Internet account will do for clients. When sockets are opened, Python is happy to use whatever connectivity you have, be it a dedicated T1 line, or a dialup modem account.
On my laptop PC, for instance, Windows automatically dials out to my ISP when clients are started or when Telnet server sessions are opened. In this book's examples, server-side programs that run remotely are executed on a machine called starship.python.net. If you don't have an account of your own on such a server, simply run client and server examples on the same machine, as shown earlier; all you need then is a computer that allows sockets, and most do.
Secondly, the socket module generally raises exceptions if you ask for something invalid. For instance, trying to connect to a nonexistent server (or unreachable servers, if you have no Internet link) fails:
C:\...\PP2E\Internet\Sockets>python echo-client.py www.nonesuch.com hello Traceback (innermost last): File "echo-client.py", line 24, in ? sockobj.connect((serverHost, serverPort)) # connect to server machine... File "<string>", line 1, in connect socket.error: (10061, 'winsock error')
Finally, also be sure to kill the server process before restarting it again, or else the port number will be still in use, and you'll get another exception:
[lutz@starship uploads]$ ps -x PID TTY STAT TIME COMMAND 5570 pts/0 S 0:00 -bash 5570 pts/0 S 0:00 -bash 5633 pts/0 S 0:00 python echo-server.py 5634 pts/0 R 0:00 ps -x [lutz@starship uploads]$ python echo-server.py Traceback (most recent call last): File "echo-server.py", line 14, in ? sockobj.bind((myHost, myPort)) # bind it to server port number socket.error: (98, 'Address already in use')
[lutz@starship uploads]$ python echo-server.py ctrl-c Traceback (most recent call last): File "echo-server.py", line 18, in ? connection, address = sockobj.accept() # wait for next client connect KeyboardInterrupt
A Ctrl-C kill key combination won't kill the server on my Windows machine, however. To kill the perpetually running server process running locally on Windows, you may need to type a Ctrl-Alt-Delete key combination, and then end the Python task by selecting it in the process listbox that appears. You can usually also kill a server on Linux with a kill -9 pid shell command if it is running in another window or in the background, but Ctrl-C is less typing.
10.3.1.6 Spawning clients in parallel
To see how the server handles the load, let's fire up eight copies of the client script in parallel using the script in Example 10-3 (see the end of Chapter 3, for details on the launchmodes module used here to spawn clients).
import sys, string from PP2E.launchmodes import QuietPortableLauncher numclients = 8 def start(cmdline): QuietPortableLauncher(cmdline, cmdline)() # start('echo-server.py') # spawn server locally if not yet started args = string.join(sys.argv[1:], ' ') # pass server name if running remotely for i in range(numclients): start('echo-client.py %s' % args) # spawn 8? clients to test the server
To run this script, pass no arguments to talk to a server listening on port 50007 on the local machine; pass a real machine name to talk to a server running remotely. On Windows, the clients' output is discarded when spawned from this script:
C:\...\PP2E\Internet\Sockets>python testecho.py C:\...\PP2E\Internet\Sockets>python testecho.py starship.python.net
If the spawned clients connect to a server run locally, connection messages show up in the server's window on the local machine:
C:\...\PP2E\Internet\Sockets>python echo-server.py Server connected by ('127.0.0.1', 1283) Server connected by ('127.0.0.1', 1284) Server connected by ('127.0.0.1', 1285) Server connected by ('127.0.0.1', 1286) Server connected by ('127.0.0.1', 1287) Server connected by ('127.0.0.1', 1288) Server connected by ('127.0.0.1', 1289) Server connected by ('127.0.0.1', 1290)
If the server is running remotely, the client connection messages instead appear in the window displaying the Telnet connection to the remote computer:
[lutz@starship lutz]$ python echo-server.py Server connected by ('126.96.36.199', 1301) Server connected by ('188.8.131.52', 1302) Server connected by ('184.108.40.206', 1308) Server connected by ('220.127.116.11', 1309) Server connected by ('18.104.22.168', 1313) Server connected by ('22.214.171.124', 1314) Server connected by ('126.96.36.199', 1307) Server connected by ('188.8.131.52', 1312)
Keep in mind, however, that this works for our simple scripts only because the server doesn't take a long time to respond to each client's requests -- it can get back to the top of the server script's outer while loop in time to process the next incoming client. If it could not, we would probably need to change the server to handle each client in parallel, or some might be denied a connection. Technically, client connections would fail after five clients are already waiting for the server's attention, as specified in the server's listen call. We'll see how servers can handle multiple clients robustly in the next section.
10.3.1.7 Talking to reserved ports
It's also important to know that this client and server engage in a proprietary sort of discussion, and so use a port number 50007 outside the range reserved for standard protocols (0-1023). There's nothing preventing a client from opening a socket on one of these special ports, however. For instance, the following client-side code connects to programs listening on the standard email, FTP, and HTTP web server ports on three different server machines:
C:\...\PP2E\Internet\Sockets>python >>> from socket import * >>> sock = socket(AF_INET, SOCK_STREAM) >>> sock.connect(('mail.rmi.net', 110)) # talk to RMI POP mail server >>> print sock.recv(40) +OK Cubic Circle's v1.31 1998/05/13 POP3 >>> sock.close() >>> sock = socket(AF_INET, SOCK_STREAM) >>> sock.connect(('www.python.org', 21)) # talk to Python FTP server >>> print sock.recv(40) 220 python.org FTP server (Version wu-2. >>> sock.close() >>> sock = socket(AF_INET, SOCK_STREAM) >>> sock.connect(('starship.python.net', 80)) # starship HTTP web server >>> sock.send('GET /\r\n') # fetch root web page 7 >>> sock.recv(60) '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\012<HTM' >>> sock.recv(60) 'L>\012 <HEAD>\012 <TITLE>Starship Slowly Recovering</TITLE>\012 </HE'
If we know how to interpret the output returned by these ports' servers, we could use raw sockets like this to fetch email, transfer files, and grab web pages and invoke server-side scripts. Fortunately, though, we don't have to worry about all the underlying details -- Python's poplib, ftplib, httplib, and urllib modules provide higher-level interfaces for talking to servers on these ports. Other Python protocol modules do the same for other standard ports (e.g., NNTP, Telnet, and so on). We'll meet some of these client-side protocol modules in the next chapter.
[lutz@starship uploads]$ python >>> from socket import * >>> sock = socket(AF_INET, SOCK_STREAM) >>> sock.bind(('', 80)) Traceback (most recent call last): File "<stdin>", line 1, in ? socket.error: (13, 'Permission denied')
Even if run by a user with the required permission, you'll get the different exception we saw earlier if the port is already being used by a real web server. On computers being used as general servers, these ports really are reserved.
|I l@ve RuBoard|