服务端

import socket
import struct
import json
import os


server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind(('172.0.0.1', 8080))

server.listen(5)

while True:
    conn, client_addr = server.accept()

    while True:
        try:

            file = conn.recv(1024)
            if len(file) == 0:
                break

            # 判断下载的文件存在与否
            if not os.path.exists(file):
                conn.send('下载链接不存在'.encode('gbk'))
                break

            # 打开文件读取数据
            with open(file, 'rb') as f:
                res = f.read()

                res_len = len(res)

            # 制作头
            header_dic = {"total_size": res_len}

            json_str = json.dumps(header_dic)
            json_str_bytes = json_str.encode('gbk')

            # 发送头的长度
            x = struct.pack('i', len(json_str_bytes))
            conn.send(x)

            # 发送头的数据
            conn.send(json_str_bytes)

            conn.send(res)
        except Exception:
            break
    conn.close()



客户端

import socket
import json
import struct


client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

client.connect(('172.0.0.1', 8080))

while True:
    file = input('请输入你要下载的文件名').strip()

    if len(file) == 0:
        continue

    client.send(file.encode('gbk'))

    # 先接收一个4,准备拿出头部信息的长度
    x = client.recv(4)
    header_len = struct.unpack('i', x)[0]

    # 有了头的长度之后,去拿头部信息里面的total_size长度
    json_str_bytes = client.recv(header_len)
    json_str = json_str_bytes.decode('gbk')
    header_dic = json.loads(json_str)
    total_size = header_dic["total_size"]

    recv_size = 0
    while total_size > recv_size:
        recv_data = client.recv(1024)
        recv_size += len(recv_data)
        print(recv_data.decode('gbk'), end='')
    print()