#!/usr/bin/env python#--*-- encoding:utf-8 --*--
importsocketserverimportosclassmyserver(socketserver.BaseRequestHandler):defhandle(self):print('wait for connect.......')
conn=self.request
addr=self.client_address
conn.sendall(bytes('欢迎使用FTP',encoding='utf-8'))whileTrue:try:
file_recv_byte=conn.recv(1024)exceptException as e:breakfile_recv_str=str(file_recv_byte,encoding='utf-8')
base_dir= os.path.dirname(__file__)
load_path=os.path.join(base_dir,file_recv_str)if notos.path.exists(os.path.dirname(load_path)):
os.mkdir(os.path.dirname(load_path))ifos.path.exists(load_path):
conn.sendall(bytes('exists',encoding='utf-8'))
pos_file_size=os.stat(load_path).st_size
file_size= int(str(conn.recv(1024),encoding='utf-8'))if file_size ==pos_file_size:
conn.sendall(bytes('已存在',encoding='utf-8'))else:
conn.sendall(bytes('可以续传', encoding='utf-8'))if str(conn.recv(1024),encoding='utf-8')=='续传':
conn.sendall(bytes(str(pos_file_size),encoding='utf-8'))
with open(load_path,'ab') as f:
recv_size=pos_file_sizewhile recv_size
data= conn.recv(1024)exceptException as e:breakf.write(data)
recv_size+=len(data)else:
conn.sendall(bytes('not exists', encoding='utf-8'))
with open(load_path,'wb') as f:
data= conn.recv(1024)
recv_size=0
file_size= int(str(data,encoding='utf-8'))
conn.sendall(bytes('ack',encoding='utf-8'))while recv_size
data= conn.recv(1024)exceptException as e:breakf.write(data)
recv_size+=len(data)
conn.close()if __name__ == '__main__':
server= socketserver.ThreadingTCPServer(('127.0.0.1',9999),myserver)
server.serve_forever()