socket模拟服务器,客户端下载东西(ftp)
服务端(ftp_server.py)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import hashlib,socket,os 2 3 server = socket.socket() 4 server.bind(("localhost",9999)) 5 server.listen() 6 while True: 7 client,address = server.accept() 8 while True: 9 req_data = client.recv(1024) 10 print(req_data.decode()) 11 if not req_data: 12 print("客户端连接已断开") 13 break 14 if len(req_data) == 0: continue 15 if os.path.isfile(req_data.decode()): 16 file_size = os.stat(req_data).st_size 17 print("file size:",file_size) 18 client.send(str(file_size).encode('utf-8')) 19 client_ack = client.recv(1024) 20 f = open(req_data,'rb') 21 for line in f: 22 m = hashlib.md5() 23 print(line) 24 client.send(line) 25 m.update(line) 26 res = m.hexdigest() 27 client.send(res.encode('utf-8')) 28 else: 29 client.send("无此文件")
客户端(ftp_client.py)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import socket,hashlib 2 3 client = socket.socket() 4 client.connect(("localhost",9999)) 5 while True: 6 cmd = input("输入文件名>>:") 7 if cmd !=None or cmd != '': 8 client.send(cmd.encode('utf-8')) 9 file_total_size = client.recv(1024) 10 print(file_total_size) 11 file_total_size = int(file_total_size) 12 client.send(b"ok") 13 curent_size = 0 14 size = 0 15 m = hashlib.md5() 16 f = open(cmd+"new",'wb') 17 while curent_size != file_total_size: 18 if file_total_size-curent_size > 1024:#不是最后一次 19 size = 1024 20 else: 21 size = file_total_size-curent_size 22 ser_info = client.recv(size) 23 print(ser_info) 24 f.write(ser_info) 25 m.update(ser_info) 26 curent_size += len(ser_info) 27 28 else: 29 print("原文件:%s,新文件:%s"%(str(file_total_size),str(curent_size))) 30 ser_md5 = client.recv(1024) 31 cli_md5 = m.hexdigest() 32 f.close() 33 print("cli_md5:%s,ser_md5:%s"%(cli_md5,ser_md5.decode()))
说明:
1.程序使用python3运行
2.明确http传输的基本概念