- The client function sends the server a file’s name and stores all the bytes it gets
back in a local file of the same name.
The most novel feature here is the protocol between client and server: the client starts
the conversation by shipping a filename string up to the server, terminated with an end-
of-line character, and including the file’s directory path in the server. At the server, a
spawned thread extracts the requested file’s name by reading the client socket, and
opens and transfers the requested file back to the client, one chunk of bytes at a time.
Running the File Server and Clients
Since the server uses threads to process clients, we can test both client and server on
the same Windows machine. First, let’s start a server instance and execute two client
instances on the same machine while the server runs:
[server window, localhost]
C:\...\Internet\Sockets> python getfile.py -mode server
Server connected by ('127.0.0.1', 59134) at Sun Apr 25 16:26:50 2010
Server connected by ('127.0.0.1', 59135) at Sun Apr 25 16:27:21 2010
[client window, localhost]
C:\...\Internet\Sockets> dir /B *.gif *.txt
File Not Found
C:\...\Internet\Sockets> python getfile.py -file testdir\ora-lp4e.gif
Client got testdir\ora-lp4e.gif at Sun Apr 25 16:26:50 2010
C:\...\Internet\Sockets> python getfile.py -file testdir\textfile.txt -port 50001
Client got testdir\textfile.txt at Sun Apr 25 16:27:21 2010
Clients run in the directory where you want the downloaded file to appear—the client
instance code strips the server directory path when making the local file’s name. Here
the “download” simply copies the requested files up to the local parent directory (the
DOS fc command compares file contents):
C:\...\Internet\Sockets> dir /B *.gif *.txt
ora-lp4e.gif
textfile.txt
C:\...\Internet\Sockets> fc /B ora-lp4e.gif testdir/ora-lp4e.gif
FC: no differences encountered
C:\...\Internet\Sockets> fc textfile.txt testdir\textfile.txt
FC: no differences encountered
As usual, we can run server and clients on different machines as well. For instance, here
are the sort of commands we would use to launch the server remotely and fetch files
from it locally; run this on your own to see the client and server outputs:
[remote server window]
[...]$ python getfile.py -mode server
842 | Chapter 12: Network Scripting