解决粘包与并发

tcp服务端

import subprocess
import os
import struct
import json
from socket import *

server = socket(AF_INET,SOCK_STREAM)
# print(server)
server.bind(('123.0.0.1',8082))
server.listen(5)
while True:
    conn,client_addr = server.accept()
    print(conn)
    print(client_addr)

    while True:
        try:
            msg = conn.recv(1024).decode('utf-8')
            cmd,file_path = msg.split()
            if cmd == 'get':
                # 一、制作报头
                header_dic={
                    "total_size":os.path.getsize(file_path),
                    "filename":os.path.basename(file_path),
                    "md5":"12312312312312312312311"
                }
                header_json=json.dumps(header_dic)
                header_json_bytes=header_json.encode('utf-8')

                # 二、发送数据
                # 1、先发送报头的长度
                header_size=len(header_json_bytes)
                conn.send(struct.pack('i',header_size))
                 # 2、再发送报头
                conn.send(header_json_bytes)
                # 3、最后发送真实的数据
                with open(r'%s'%file_path,mode='rb')as f:
                    for line in f:
                        conn.send(line)
        except Exception:
            break
    conn.close()
server.close()

tcp客户端

import struct
import json
from socket import *

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

while True:
    cmd = input(">>: ").strip()  # get文件路径
    if len(cmd) == 0:
        continue
    client.send(cmd.encode('utf-8'))

    # 1 先接收报头的长度
    res = client.recv(4)
    header_size = struct.unpack('i',res)[0]

    # 2、再接收报头
    header_json_bytes = client.recv(header_size)
    header_json=header_json_bytes.decode('utf-8')
    header_dic=json.loads(header_json)
    print(header_dic)
    # 3、最后接收真实的数据
    total_size = header_dic['total_size']
    filename= header_dic['filename']
    recv_size = 0
    with open(r"D:\python全栈15期\day32\代码\03 定制复杂的报头\版本2\download\%s" %filename,mode='wb')as f:
        while recv_size < total_size:
            data = client.recv(1024)
            f.write(data)
            recv_size +=len(data)
client.close()

你可能感兴趣的:(笔记,编程)