解决粘包问题的终极大招

服务端

import socket
import struct
import subprocess
import json

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

while True:
    conn,client_addr = server.accept()
    print('客户端的ip和端口是:',client_addr)

    while True:
        try:
            data = conn.recv(1024)
            if len(data) == 0:break
            print('客户端发来的消息是:',data.decode('utf-8'))

            res = subprocess.Popen(
                data.decode('utf-8'),
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            stdout_res = res.stdout.read()
            stderr_res = res.stderr.read()
            res_size = len(stdout_res) + len(stderr_res)
            print('服务端返回消息的长度为:',res_size)

            header_dic = {
                'filename':'aa.txt',
                'filesize':res_size,
                'md5':'fadsj54335k5432k5lh5jk23j4jk'
            }

            header_dic_str = json.dumps(header_dic)
            header_dic_str_bytes = header_dic_str.encode('utf-8')
            header_dic_str_bytes_struct = struct.pack('i',len(header_dic_str_bytes))

            conn.send(header_dic_str_bytes_struct)
            conn.send(header_dic_str_bytes)
            conn.send(stdout_res)
            conn.send(stderr_res)

        except Exception:
            break
    conn.close()
server.close()

 

 

客户端

import socket
import struct
import json

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

while True:
    msg = input('cmd:').strip()
    if len(msg) == 0:continue
    client.send(msg.encode('utf-8'))

    header_dic_str_bytes_struct = client.recv(4)
    header_dic_str_bytes_size = struct.unpack('i',header_dic_str_bytes_struct)[0]
    header_dic_str_bytes = client.recv(header_dic_str_bytes_size)
    header_dic_str = header_dic_str_bytes.decode('utf-8')
    header_dic = json.loads(header_dic_str)
    print(header_dic)
    total_size = header_dic['filesize']
    recv_size = 0
    while recv_size < total_size:
        recv_data = client.recv(1024)
        recv_size += len(recv_data)
        print('服务端发来的消息是:',recv_data.decode('gbk'))
    else:
        print('客户端收到的消息长度是:',recv_size)
client.close()

 

上一篇:TCP 传输数据终极版(解决粘包问题)


下一篇:ART-PI调试记录