发送大数据文件
Posted asdaa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发送大数据文件相关的知识,希望对你有一定的参考价值。
客户端
import os import socket import struct import json client = socket.socket() client.connect((‘127.0.0.1‘, 8080)) while True: movie_dir = r‘F:\day31\视频‘ movie_list = os.listdir(movie_dir) for index, i in enumerate(movie_list, 1): print(index, i) choice = input(‘请输入你想选择影片的编号:‘).strip() if not choice.isdigit(): print(‘请输入数字‘) continue choice = int(choice) - 1 if choice not in range(0, len(movie_list)): print(‘请输入正确数字‘) continue movie_name = movie_list[choice] movie_path = os.path.join(movie_dir, movie_name) # 获取文件大小 movie_size = os.path.getsize(movie_path) # 制作字典 dic = ‘name‘: movie_name, ‘movie_size‘: movie_size # 制作报头 json_dic = json.dumps(dic) byte_dic = json_dic.encode(‘utf-8‘) header = struct.pack(‘i‘, len(byte_dic)) # 发送报头 client.send(header) # 发送字典 client.send(byte_dic) # 发送真实数据 with open(movie_path, ‘rb‘)as f: res = f.readlines() for i in res: client.send(i) print(‘xxx‘)
服务端
import socket import json import struct server = socket.socket() server.bind((‘127.0.0.1‘, 8080)) server.listen(5) while True: conn, addre = server.accept() while True: try: # 接收字典报头 header_dic = conn.recv(4) # 解析报头获取字典长度 dic_size = struct.unpack(‘i‘, header_dic)[0] print(dic_size) # 接收字典 byte_dic = conn.recv(dic_size) dic = json.loads(byte_dic.decode(‘utf-8‘)) # 接收真实数据 real_size = dic.get(‘movie_size‘) recv_size = 0 while recv_size < real_size: data = conn.recv(1024) with open(r‘D:\unloads\%s‘ % dic.get(‘name‘), ‘ab‘)as f: f.write(data) recv_size += len(data) print(‘ooo‘) except ConnectionResetError: break
以上是关于发送大数据文件的主要内容,如果未能解决你的问题,请参考以下文章