python ftp
#fpt_server.py
#__*__ encoding=utf-8 __*__ import socket ,os class MyClass(object): def __init__(self): print('server start.....') server = socket.socket() server.bind(('localhost',8888)) server.listen() while True: conn, addr = server.accept() print("new conn:",addr) while True: print("等待新指令") data = conn.recv(1024) if not data: print("客户端已断开") break cmd,filename = data.decode().split() print(filename) if os.path.isfile(filename): #�ж��Ƿ����ļ� f = open(filename,"rb") #���ļ� file_size = os.stat(filename).st_size #�ļ���С conn.send( str(file_size).encode() ) #send file size ��ֹճ�� conn.recv(1024) #wait for ack for line in f: conn.send(line) #��ʼ���� f.close() print("send done") server.close()
#ftp_client.py #__*__ encoding=utf-8 __*__ import socket import hashlib from gettext import find class MyClass(object): def __init__(self): print('client start....') client = socket.socket() client.connect(('localhost', 8888)) targetpath='E:\\python\\recievedir' while True: cmd = input(">>:").strip() if len(cmd) == 0: print('test cmd len is 0') continue if cmd.startswith("get"): #判断是否以字符串‘get’ 开头 client.send(cmd.encode()) #把需要下载的文件发给server端 server_response = client.recv(1024) #接收server端发过来的文件大小 print("servr response:", server_response) #打印文件大小 client.send(b"ready to recv file") #防止粘包 file_total_size = int(server_response.decode()) print(file_total_size) received_size = 0 #已经接收的大小 filename = cmd.split()[1] targetname=filename targetname=MyClass.retFileWithType('',targetname) f = open(targetpath+'\\'+targetname + ".new", "wb") #创建新文件 用于保存 # f = open(filename + ".new", "wb") #创建新文件 用于保存 while received_size < file_total_size: if file_total_size - received_size > 1024: # 要收不止一次 size = 1024 else: # 最后一次了,剩多少收多少 size = file_total_size - received_size print("last receive:", size) data = client.recv(size) received_size += len(data) f.write(data) # print(file_total_size,received_size) else: print("file recv done", received_size, file_total_size) f.close() client.close() def retFileWithType(self,xname): # xname=r'E:\\python\\recievedir\\data.pkl' # xname=r'E:\python\test.jpg' # print(xname) xname=repr(xname) FileWithType="" try: if xname.index(r'\\')>0 : xname=xname.replace(r'\\', '\\') x=xname.rfind('\\') # print(x,xname[x+1:]) retFileWithType=xname[x+1:] except (ValueError) as e: xname=xname.replace('\\', r"\\") x=xname.rfind(r'\\') # print(x,xname[x+2:]) retFileWithType=xname[x+2:] retFileWithType = retFileWithType.replace("\'",'') return retFileWithType