FTP-成型版本
1. 旧知识回顾-反射
hasattr(object, name)
说明:判断对象object是否包含名为name的属性(方法)
测试代码如下:
class tt(object): def __init__(self): pass def AA(self): self.name='Lucy' def tes(self): while True: cmd=input(">>:").strip() if hasattr(self,cmd): #用来判断对象object的属性(name表示)是否存在。 print('Yes,we have fun %s'%cmd) else: print("nonono...,we don't have this fun") obj=tt() obj.tes()
运行结果:
>>:AA Yes,we have fun AA >>:test nonono...,we don't have this fun >>:b nonono...,we don't have this fun >>:
2. 自己写的
服务器端脚本
import socketserver,os,json class MYTCP(socketserver.BaseRequestHandler): #定义一个请求处理类 def handle(self): #重写handle函数 while True: try: self.data=self.request.recv(1024) cmd_dic=json.loads(self.data.decode()) action=cmd_dic['action'] if hasattr(self,action): func=getattr(self,action) func(cmd_dic) except ConnectionResetError as e: print("Error is:",e) break def put(self,*args): cmd_dic=args[0] filename=cmd_dic['filename'] filesize=cmd_dic['filesize'] if os.path.isfile(filename): #如果服务器上已经存在,则建一个新的 f=open(filename+'.new','wb') else: f=open(filename,'wb') self.request.send(b'be ready to receive') received_size=0 while received_size<filesize: data=self.request.recv(1024) received_size+=len(data) f.write(data) else: f.close() print("upload successfully") server=socketserver.ThreadingTCPServer(('localhost',9999),MYTCP) #实例化一个服务类 server.serve_forever() #调用服务类下面的serve_forever方法
客户端脚本:
import os,json,socket class FtpClient(object): def __init__(self): self.client=socket.socket() def help(self): msg=''' ls pwd cd.. put filename get filename ''' print(msg) def connect(self,ip,port): self.client.connect((ip,port)) def interactive(self): while True: cmd=input(">>:").strip() if len(cmd)==0:continue cmd_str=cmd.split()[0] if hasattr(self,'cmd_%s'%cmd_str): func=getattr(self,'cmd_%s'%cmd_str) func(cmd) else: self.help() def cmd_put(self,*args): cmd_split=args[0].split() if len(cmd_split)>1: filename = cmd_split[1] if os.path.isfile(filename): filesize=os.stat(filename).st_size cmd_dic={ 'action':'put', 'filename':filename, 'filesize':filesize, 'overridden':True } self.client.send(json.dumps(cmd_dic).encode()) server_response=self.client.recv(1024) f=open(filename,'rb') for line in f: self.client.send(line) else: f.close() print('upload successfully') def cmd_get(self,*args): pass ftp=FtpClient() ftp.connect('localhost',9999) ftp.interactive()