#7512import socket,os,json,time,hashlibclient_addr = ("localhost", 9999)class MyTCPClient(object): socket_family = socket.AF_INET socket_type = socket.SOCK_STREAM messge = [0, ] MYBASS = os.path.abspath("..\log\client") def __init__(self,addr,numb): self.sock = [socket.socket(self.socket_family,self.socket_type) for i in range(numb)] self.connect(addr) self._addr = 'copy' print('''------------------Welcome!!-------------- (help:帮助信息) ''') self.interation() def connect(self,addr): for client in self.sock: client.connect(addr) # client.setblocking(False) def interation(self): while True: for client in self.sock: com = input(">>:").strip() if len(com) == 0: continue com = com.split() if hasattr(self,'com_%s'%com[0]): func = getattr(self,'com_%s'%com[0]) func(com,client) else: client.send(json.dumps(com).encode()) print("recv data [%s]"%client.recv(1024).decode()) def com_put(self,com,client): if os.path.isfile(com[1]): com_data ={} com_data["action"] = com[0] com_data["file"] = com[1] com_data["error"] = '0' com_data["size"] = str(os.stat(com_data["file"]).st_size) client.send(json.dumps(com_data).encode()) file_obj = open(com_data["file"] , 'rb') md5 = hashlib.md5() if client.recv(2) == b'ok': for line in file_obj: md5.update(line) client.send(line) client.send(md5.hexdigest().encode()) print("put the file suceesful!") else: print("File does not exist... ") self.interation() pass def com_get(self,com,client): ''' 客户端下载函数,com为指令,client为客户端实例 :param com: :param client: :return: ''' #要下载的文件信息,需要发给服务端 com_data ={} com_data["action"] = com[0] com_data["file"] = com[1] com_data["error"] = '0' com_data["size"] = "0" client.send(json.dumps(com_data).encode()) #判断文件是否存在,并接收文件大小 get_info = client.recv(1024) get_info = json.loads(get_info.decode()) print("back data:",get_info) error =get_info["error"] #文件存在 if error == '0': filesize = int(get_info["size"]) print("will get the file size is [%s]" % filesize) #是否覆盖 if os.path.isfile(self._addr): self._addr += '_new' #打开文件 # get_file = open("F:\Python\s1\\task\selectFTP\data\copy", 'wb') get_file = open(self._addr, 'wb') recv_size = 0 size = 0 md5 = hashlib.md5() #开始下载 client.send(b'ok') while recv_size < filesize: if filesize - recv_size >1024: size = 1024 else: size = filesize - recv_size data = client.recv(size) get_file.write(data) get_file.flush() recv_size += len(data) md5.update(data) less = int(float(recv_size/filesize)*100) print("file get now %s "%str(less)) # time.sleep(5) else: #文件校验,检查是否接收出错 check_md5 = client.recv(1024) print("\033[31;1m [%s] \033[0m \033[30;1m [%s] \033[0m"%(md5.hexdigest(),check_md5)) if md5.hexdigest() == check_md5: print("get the file successful!") get_file.close() else: print("File does not exist... ") self.interation() def com_help(self,com,client): print(''' put 文件名 上传文件 get 文件名 下载文件 其他命令 返回大写''')if __name__ =="__main__": c= MyTCPClient(client_addr,1)
来源:https://www.cnblogs.com/gtq7512/p/11396783.html