[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

sock.send((filename + '\n').encode()) # send remote name with dir: bytes
dropdir = os.path.split(filename)[1] # filename at end of dir path
file = open(dropdir, 'wb') # create local file in cwd
while True:
data = sock.recv(blksz) # get up to 1K at a time
if not data: break # till closed on server side
file.write(data) # store data in local file
sock.close()
file.close()
print('Client got', filename, 'at', now())


def serverthread(clientsock):
sockfile = clientsock.makefile('r') # wrap socket in dup file obj
filename = sockfile.readline()[:-1] # get filename up to end-line
try:
file = open(filename, 'rb')
while True:
bytes = file.read(blksz) # read/send 1K at a time
if not bytes: break # until file totally sent
sent = clientsock.send(bytes)
assert sent == len(bytes)
except:
print('Error downloading file on server:', filename)
clientsock.close()


def server(host, port):
serversock = socket(AF_INET, SOCK_STREAM) # listen on TCP/IP socket
serversock.bind((host, port)) # serve clients in threads
serversock.listen(5)
while True:
clientsock, clientaddr = serversock.accept()
print('Server connected by', clientaddr, 'at', now())
thread.start_new_thread(serverthread, (clientsock,))


def main(args):
host = args.get('-host', defaultHost) # use args or defaults
port = int(args.get('-port', defaultPort)) # is a string in argv
if args.get('-mode') == 'server': # None if no -mode: client
if host == 'localhost': host = '' # else fails remotely
server(host, port)
elif args.get('-file'): # client mode needs -file
client(host, port, args['-file'])
else:
print(helptext)


if name == 'main':
args = parsecommandline()
main(args)


This script isn’t much different from the examples we saw earlier. Depending on the
command-line arguments passed, it invokes one of two functions:



  • The server function farms out each incoming client request to a thread that trans-
    fers the requested file’s bytes.


A Simple Python File Server | 841
Free download pdf