文件下载的逻辑和上传的逻辑是一样的。这里以文件的上传为例

client:

import socket
import os
import struct
import json

sk = socket.socket()
sk.connect(("127.0.0.1", 8123))

# 要发送的文件
file_path = "my_socket_util.py"

# 拿到文件大小和文件名字
file_size = os.path.getsize(file_path)
file_name = os.path.basename(file_path)

# 组装一个字典.
file_json = {"file_name": file_name, "file_size": file_size}
# 转化成json字符串, 里面存着数据
file_json_str = json.dumps(file_json)
# 把json字符串发送出去. 防止黏包. 需要先发送数据大小
file_json_bs = file_json_str.encode("utf-8")
file_len_bs = struct.pack("i", len(file_json_bs))
sk.send(file_len_bs)

# 发送json数据
sk.send(file_json_bs)

# 发送文件数据
with open(file_path, mode="rb") as f:
    while file_size > 0:
        bs = f.read(1024)  # 每次最多发送1024个字节
        sk.send(bs)
        file_size -= len(bs)  # 发一次少一些字节

print("上传完毕")
sk.close()

server:

import socket
import struct
import json

sk = socket.socket()
sk.bind(("127.0.0.1", 8123))
sk.listen()

conn, address = sk.accept()

# 接收json长度, 放黏包
file_json_len_bs = conn.recv(4)
file_json_len = struct.unpack("i", file_json_len_bs)[0]
# 获取json字符串
file_json_str = conn.recv(file_json_len).decode('utf-8')
# 转化回字典
file_json = json.loads(file_json_str)

with open(f"上传/{file_json['file_name']}", mode="wb") as f:
    while file_json['file_size'] > 0:
        bs = conn.recv(1024)
        file_json['file_size'] -= len(bs)
        f.write(bs)
        print("one part")

print("上传完毕")
sk.close()