史上最简单的ftp下载服务器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了史上最简单的ftp下载服务器相关的知识,希望对你有一定的参考价值。
#ftp服务端代码
````
# encoding:utf-8
# Author:"richie"
# Date:8/23/2017
from socket import *
import pickle
import os
server=(‘127.0.0.1‘,17001)
root_path= os.path.abspath(os.curdir) # The absolute path of the current folder
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(server)
sock.listen(5)
print(‘Wait for the client connection!!!‘)
while True: # Link cycle
conn, addr = sock.accept() #Waiting for client connection
print(‘Connect by‘,addr)
while True: # Communication cycle
try:
data = conn.recv(1024) # Receive client data
if not data: break
filename = data.decode(‘utf-8‘) # Bytes -> String
file_path = os.path.join(root_path,filename) # join path
# get file size if file not existed file size is zero
file_size = os.path.getsize(file_path) if os.path.exists(file_path) else 0
header = pickle.pack(‘q‘, file_size) # pack header
conn.send(header) # send header
if file_size: #The file exists and size than 0
with open(file_path,‘rb‘) as f:
for line in f:
conn.send(line) # send line of file data
else:
conn.send(b‘‘)
except ConnectionResetError as e: # conn abnormal
break
except Exception as e:
print(e)
conn.close()
````
#ftp客户端代码
````
# encoding:utf-8
# Author:"richie"
# Date:8/23/2017
from socket import *
import pickle,sys
import os
def progress(percent,width=250):
if percent >= 100:
percent=100
show_str=(‘[%%-%ds]‘ %width) %(int(width * percent / 100) * "#") #字符串拼接的嵌套使用
print("\r%s %d%%" %(show_str, percent),end=‘‘,file=sys.stdout,flush=True)
server=(‘127.0.0.1‘,17001)
sock = socket(AF_INET,SOCK_STREAM)
sock.connect(server)
root_path= os.path.abspath(os.curdir) # The absolute path of the current folder
while True:
print(‘The current home path is ‘+root_path)
filename = input(‘Please enter the path>>:‘).strip()
if not filename:continue
sock.send(filename.encode(‘utf-8‘))
header = sock.recv(8) # Receive the header
total_size = pickle.unpack(‘q‘,header)[0] # get header data
each_recv_size = 1024*8421
recv_size = 0
recv_data = b‘‘
down_filename = ‘down_‘+filename
f = open(down_filename,‘wb‘)
while recv_size < total_size:
if total_size - recv_size < each_recv_size:
data = sock.recv(total_size - recv_size)
else:
data = sock.recv(each_recv_size)
recv_size += len(data)
recv_percent = int(100 * (recv_size / total_size)) # Receive the percent
progress(recv_percent, width=30) # The width of the progress bar is 30
f.write(data)
print()
f.close()
````
本文出自 “richiewen” 博客,请务必保留此出处http://richiewen.blog.51cto.com/12233798/1958958
以上是关于史上最简单的ftp下载服务器的主要内容,如果未能解决你的问题,请参考以下文章