1. 程式人生 > >史上最簡單的ftp下載服務器

史上最簡單的ftp下載服務器

spa 最簡 pre 服務器 pat ror tin total true

服務端:

 1 # encoding:utf-8
 2 # Author:"richie"
 3 # Date:8/23/2017
 4 
 5 from socket import *
 6 import pickle
 7 import os
 8 
 9 server=(127.0.0.1,17001)
10 root_path= os.path.abspath(os.curdir) # The absolute path of the current folder
11 sock = socket(AF_INET, SOCK_STREAM)
12 sock.bind(server)
13 sock.listen(5)
14 print(Wait for the client connection!!!) 15 while True: # Link cycle 16 conn, addr = sock.accept() #Waiting for client connection 17 print(Connect by,addr) 18 while True: # Communication cycle 19 try: 20 data = conn.recv(1024) # Receive client data 21 if
not data: break 22 filename = data.decode(utf-8) # Bytes -> String 23 file_path = os.path.join(root_path,filename) # join path 24 # get file size if file not existed file size is zero 25 file_size = os.path.getsize(file_path) if os.path.exists(file_path) else
0 26 header = pickle.pack(q, file_size) # pack header 27 conn.send(header) # send header 28 if file_size: #The file exists and size than 0 29 with open(file_path,rb) as f: 30 for line in f: 31 conn.send(line) # send line of file data 32 else: 33 conn.send(b‘‘) 34 except ConnectionResetError as e: # conn abnormal 35 break 36 except Exception as e: 37 print(e) 38 conn.close()

客戶端

 1 # encoding:utf-8
 2 # Author:"richie"
 3 # Date:8/23/2017
 4 
 5 from socket import *
 6 import pickle,sys
 7 import os
 8 def progress(percent,width=250):
 9     if percent >= 100:
10         percent=100
11     show_str=([%%-%ds] %width) %(int(width * percent / 100) * "#") #字符串拼接的嵌套使用
12     print("\r%s %d%%" %(show_str, percent),end=‘‘,file=sys.stdout,flush=True)
13 
14 server=(127.0.0.1,17001)
15 sock = socket(AF_INET,SOCK_STREAM)
16 sock.connect(server)
17 root_path= os.path.abspath(os.curdir) # The absolute path of the current folder
18 
19 while True:
20     print(The current home path is +root_path)
21     filename = input(Please enter the path>>:).strip()
22     if not filename:continue
23     sock.send(filename.encode(utf-8))
24     header = sock.recv(8) # Receive the header
25     total_size = pickle.unpack(q,header)[0] # get header data
26     each_recv_size = 1024*8421
27     recv_size = 0
28     recv_data = b‘‘
29     down_filename = down_+filename
30     f = open(down_filename,wb)
31     while recv_size < total_size:
32         if total_size - recv_size < each_recv_size:
33             data = sock.recv(total_size - recv_size)
34         else:
35             data = sock.recv(each_recv_size)
36         recv_size += len(data)
37         recv_percent = int(100 * (recv_size / total_size))  # Receive the percent
38         progress(recv_percent, width=30)  # The width of the progress bar is 30
39         f.write(data)
40     print()
41     f.close()

史上最簡單的ftp下載服務器