A Simple Python File Server
It’s time for something realistic. Let’s conclude this chapter by putting some of the
socket ideas we’ve studied to work doing something a bit more useful than echoing
text back and forth. Example 12-17 implements both the server-side and the 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 12-17. PP4E\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, time, _thread as thread
from socket import *
blksz = 1024
defaultHost = 'localhost'
defaultPort = 50001
helptext = """
Usage...
server=> getfile.py -mode server [-port nnn] [-host hhh|localhost]
client=> getfile.py [-mode client] -file fff [-port nnn] [-host hhh|localhost]
"""
def now():
return time.asctime()
def parsecommandline():
dict = {} # put in dictionary for easy lookup
args = sys.argv[1:] # skip program name at front of args
while len(args) >= 2: # example: dict['-mode'] = 'server'
dict[args[0]] = args[1]
args = args[2:]
return dict
def client(host, port, filename):
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
840 | Chapter 12: Network Scripting