网络编程- struct模块定制报头ftp实践(九)

一、server端
import json
import struct
import socket

sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()

conn,addr = sk.accept()
dic_len = conn.recv(4) # 4个字节 数字的大小
dic_len = struct.unpack('i',dic_len)[0]
content = conn.recv(dic_len).decode('utf-8') # 70
content_dic = json.loads(content)
if content_dic['operate'] == 'upload':
with open(content_dic['filename'],'wb') as f:
while content_dic['filesize']:
file = conn.recv(1024)
f.write(file)
content_dic['filesize'] -= len(file)
conn.close()
sk.close()

client端
import os
import json
import struct
import socket

sk = socket.socket()
sk.connect(('127.0.0.1',8080))

def get_filename(file_path):
filename = os.path.basename(file_path)
return filename

#选择 操作
operate = ['upload','download']
for num,opt in enumerate(operate,1):
print(num,opt)
num = int(input('请输入您要做的操作序号 : '))
if num == 1:
'''上传操作'''
file_path = input('请输入要上传的文件路径 : ')
file_size = os.path.getsize(file_path) # 获取文件大小
file_name = get_filename(file_path)
dic = {'operate': 'upload', 'filename': file_name,'filesize':file_size}
str_dic = json.dumps(dic).encode('utf-8')
ret = struct.pack('i', len(str_dic)) # 将字典的大小转换成一个定长(4)的bytes
sk.send(ret + str_dic)
with open(file_path,'rb') as f:
while file_size:
content = f.read(1024)
sk.send(content)
file_size -= len(content)
elif num == 2:
'''下载操作'''
sk.close()





二、win系统下传每次buffer=4096有报错情况猜测(改成1024解决)

修改前
server端(buffer=4096)
第二个head_len的后面加[0]获取元组第一个数

    

client端



 
修改后
server端(buffer=1024)

     

client端(buffer改成1024)

  

 



posted @   大圣原来姓毛  阅读(151)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· 赶AI大潮:在VSCode中使用DeepSeek及近百种模型的极简方法
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
点击右上角即可分享
微信分享提示