点击上方蓝字关注我!
图片来源 pexels.com
简单实现文件上传、下载
1
Server端
# -*- coding: utf-8 -*-import jsonimport os__author__ = 'sange'# @Time : 2020/8/17 下午5:26# @Author : 'sange'# @File : tcpserver_socket.py# @Software: PyCharmimport socketserverclass MyTCPHandler(socketserver.BaseRequestHandler): def put(self,*args): ''' 接收客户端传过来的文件''' cmd_dict = args[0] filename= cmd_dict["filename"] filenameSize = cmd_dict["fileSize"] if os.path.isfile(filename): f = open(filename + "-new","wb") else: f = open(filename,"wb") self.request.send(b"200 ok") recved_size = 0 while recved_size < filenameSize: recv_data = self.request.recv(1024) f.write(recv_data) recved_size+=len(recv_data) else: print("file [%s] has uploaded..." % filename) def handle(self): while True: try: self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.client_address[0])) print(self.data) if not self.data: break cmd = json.loads(self.data.decode()) action= cmd["action"] if hasattr(self,action): doaction=getattr(self,action) doaction(cmd) except ConnectionResetError as e: print("err",e) break def get(self,*args): fileName = args[0]["fileName"] if os.path.isfile(fileName): file_size = os.path.getsize(fileName) self.request.send(str(file_size).encode("utf-8")) # 发送给客户端文件大小 self.request.recv(1024) # wait client send 粘包 f = open(fileName,"rb") for line in f: self.request.send(line) f.close() print("[" + fileName + "]" + "文件发送完毕。。。。。。。")if __name__ == "__main__": ip_port = ("localhost", 8000) s = socketserver.ThreadingTCPServer(ip_port,MyTCPHandler) s.serve_forever()
2
Client端
# -*- coding: utf-8 -*-import jsonimport random__author__ = 'sange'# @Time : 2020/8/17 下午5:44# @Author : 'sange'# @File : tcpserver_client.py# @Software: PyCharm''''''import socket,os,sysclass FtpClient(object): def __init__(self): self.client = socket.socket() def connect(self,ip,port): ''' connet server :param ip: :param port: :return: ''' self.client.connect((ip,port)) def help(self): msg = ''' ls pwd cd put filename get filename ''' print(msg) def jiaohu(self): ''' send cmd to server,and recv server return result ''' while True: cmd_input = input("输入要执行的操作==>").strip() if len(cmd_input) == 0:continue cmd_action = cmd_input.split()[0] #获取命令执行相应的方法 如 get test.py执行下面的get方法,put则执行下面的put方法 if hasattr(self,"cmd_%s" % cmd_action): func = getattr(self,"cmd_%s" % cmd_action) func(cmd_input) else: self.help() def cmd_put(self,*args): #解析命令参数,put filename cmd_ac = args[0].split() if len(cmd_ac) > 1: filename = cmd_ac[1] if os.path.isfile(filename): fileSize = os.path.getsize(filename) put_param = { "fileSize":fileSize, "action":"put", "filename":filename } self.client.send(json.dumps(put_param).encode("utf-8")) #防止粘包,等服务器确认 recv = self.client.recv(1024) f = open(filename,"rb") for line in f: self.client.send(line) else: print("%s file upload success" % filename) f.close() else: print("%s file is not exist"%filename) def cmd_get(self,*args): ''' get filename''' cmd_inp = args[0] # get test fileName = cmd_inp.split()[1] json_get = { "fileName":fileName, "action":"get" } self.client.send(json.dumps(json_get).encode("utf-8")) server_response = self.client.recv(1024) print("servr response:", server_response) self.client.send(b"ready to recv file") file_total_size = int(server_response.decode()) received_size = 0 f = open(fileName+'-'+str(random.randint(100000,900000)), 'wb') while received_size < file_total_size: if file_total_size - received_size > 1024: size = 1024 else: size = file_total_size - received_size data = self.client.recv(size) received_size += len(data) f.write(data) else: print("cmd res receive done...", received_size) f.close()if __name__ == "__main__": f = FtpClient() f.connect("localhost",8000) f.jiaohu()
------------------------end-----------------------
扫码关注 获取更多