基于socket套接字上传大文件
server端(服务端)
import socketimport structimport jsonserver = socket.socket()server.bind(('127.0.0.1', 8080))server.listen(5)while True: conn, addr = server.accept() while True: try: hander = conn.recv(4) print('报头',hander) if hander == 0: break # 解析报头,并获取字典长度 dic_len = struct.unpack('i', hander)[0] # 获得字典内容 real_dic = json.loads(conn.recv(dic_len)) # 从字典中获取 真实文件名和大小 file_name = real_dic.get('file_name') file_size = real_dic.get('file_size') # 接受真实数据并保存到文件中 with open(file_name, 'wb') as f: size = 0 while size < file_size: res = conn.recv(1024) size += len(res) f.write(res) print('接受成功') break except ConnectionResetError: break
client端(客户端)
import socketimport jsonimport structimport osclient = socket.socket()client.connect(('127.0.0.1', 8080))# 获得文件名和文件大小while True: dir_list = os.listdir(r'F:\pycharm文档\5.18\文件库') # 打印出可选上传文件 [print(k,v) for k,v in enumerate(dir_list,start=1)] choice = input('>>>:') if choice in ['1','2']: file_name = dir_list[int(choice) - 1] print('文件名:',file_name) file_path = os.path.join(r'F:\pycharm文档\5.18\文件库',file_name) # 得到文件大小 file_size = os.path.getsize(file_path) print('文件大小:',file_size) break else: print('again')# 制作报头字典内容dic = { 'file_name':file_name, 'file_size':file_size}dic_json = json.dumps(dic)dic_json_bytes = dic_json.encode('utf8')# 制作字典的报头hander = struct.pack('i',len(dic_json_bytes))client.send(hander)client.send(dic_json_bytes)# 发送真实数据with open(file_path,'rb') as f: for line in f: client.send(line)client.close()