自定义协议+解决粘包作业

服务端

import json,struct,os
from socket import *


sever = socket(AF_INET,SOCK_STREAM)
sever.bind(('127.0.0.1',8080))
sever.listen(5)

# 图片的路径:
image_path = r'C:UsersadminDesktoppython视频图片.jpg'  #(写死了,只能下载我电脑上的图片)

while True:
    conn,clint_addr = sever.accept()
    while True:
        try:
            cmd = conn.recv(1024)
            if not cmd:break
            total_size = os.path.getsize(image_path)

            header_dic = {
                "filename": "python视频图片.jpg",
                "total_size": total_size,
            }
            json_str = json.dumps(header_dic)
            json_str_bytes = json_str.encode('utf-8')
            x = struct.pack('i', len(json_str_bytes))
            conn.send(x)
            conn.send(json_str_bytes)
            with open(image_path, 'rb') as f:
                for line in f:
                    conn.send(line)

        except Exception:
            break
    conn.close()

  

客户端

import json,struct,os
from socket import *

client = socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))

# 指定下载路径
down_path = r'C:UsersadminDesktop刚下载的图片.jpg'

while True:
    cmd=input('请输入命令(只能下载我服务端的图片)>>:').strip()
    if len(cmd) == 0:continue
    client.send(cmd.encode('utf-8'))

    # 接收端
    # 1、先手4个字节,从中提取接下来要收的头的长度
    x=client.recv(4)
    header_len=struct.unpack('i',x)[0]

    # 2、接收头,并解析
    json_str_bytes=client.recv(header_len)
    json_str=json_str_bytes.decode('utf-8')
    header_dic=json.loads(json_str)
    print(header_dic)
    total_size=header_dic["total_size"]

    # 3、接收真实的数据
    recv_size = 0
    with open(down_path,'wb') as f:
        while recv_size < total_size:
            recv_data=client.recv(1024)
            recv_size+=len(recv_data)
            f.write(recv_data)
        else:
            print('下载成功')

  

原文地址:https://www.cnblogs.com/Tornadoes-Destroy-Parking-Lots/p/12748298.html