A Simple Python File Server

Time for something more realistic. Let’s conclude this chapter by putting some of these socket ideas to work in something a bit more useful than echoing text back and forth. Example 10-10 implements both the server-side and client-side logic needed to ship a requested file from server to client machines over a raw socket.

In effect, this script implements a simple file download system. One instance of the script is run on the machine where downloadable files live (the server), and another on the machines you wish to copy files to (the clients). Command-line arguments tell the script which flavor to run and optionally name the server machine and port number over which conversations are to occur. A server instance can respond to any number of client file requests at the port on which it listens, because it serves each in a thread.

Example 10-10. PP2E\Internet\Sockets\getfile.py

######################################################## # implement client and server side logic to transfer an # arbitrary file from server to client over a socket; # uses a simple control-info protocol rather than # separate sockets for control and data (as in ftp), # dispatches each client request to a handler thread, # and loops to transfer the entire file by blocks; see # ftplib examples for a higher-level transport scheme; ######################################################## import sys, os, thread, time from socket import * def now(): return time.ctime(time.time()) blksz ...

Get Programming Python, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.