使用socket实现的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()

客户端

 # 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()
上一篇:iOS7应用开发1、菜鸟那点儿事儿


下一篇:Http协议之Get和Post的区别