实现一个简单的ftp文件上传功能
作者:互联网
# 接收端
# 服务端 import json import socket import struct sk = socket.socket() sk.bind(('127.0.0.1', 8080)) sk.listen() conn, addr = sk.accept() buffer = 1024 head_len = conn.recv(4) head_len = struct.unpack('i', head_len) header = conn.recv(head_len[0]).decode('utf-8') header = json.loads(header) filesize = header['filesize'] with open(header['filename'],'wb') as f: while header['filesize']: if header['filesize'] >= buffer: conent = conn.recv(buffer) f.write(conent) header['filesize'] -= buffer print(header['filesize']) else: conent = conn.recv(header['filesize']) f.write(conent) break
# 上传端
# 客户端 import json import os import socket import struct sk = socket.socket() sk.connect(('127.0.0.1', 8080)) buffer = 1024 header = {'filepath': r'E:\文档\工作\需求视频\IWB业务视频\IWB业务视频', 'filename': r'01_IDEC_DDEC文件导入.mp4', 'filesize': None} file_path = os.path.join(header['filepath'], header['filename']) header['filesize'] = os.path.getsize(file_path) header_json = json.dumps(header) # 先计算header报头的长度 # 发送header报头的长度,把数字转换成固定长度的bytes sk.send(struct.pack('i', len(header_json.encode('utf-8')))) # 再发送header报头 sk.send(header_json.encode('utf-8')) # 再发送报文内容 with open(file_path,'rb') as f: while header['filesize']: if header['filesize'] >= buffer: content = f.read(buffer) sk.send(content) header['filesize'] -= buffer print(header['filesize']) else: content = f.read(header['filesize']) break
标签:ftp,文件,buffer,sk,header,json,filesize,import,上传 来源: https://www.cnblogs.com/leev1-01/p/16470730.html