协议打包

# -*- coding:utf-8 -*-

import struct

def pack(command_id, sequence, session_id, body):
    """
    网络传输
    @param command_id: 协议编号
    @param sequence: 序列号
    @param session_id: 
    @param body: 包体,str类型
    
    @return: 二进制串
    """
    
    header_size, header_data = pack_header(command_id, sequence, session_id)
    body_size, body_data = pack_body(body)
    size = header_size + body_size
    data = struct.pack('!I', size) + header_data + body_data
    return data

def pack_header(command_id, sequence, session_id):
    """
    包头
    """
    if isinstance(session_id, unicode):
        session_id.encode('utf-8')
    fmt = '!IIB%ds' % len(session_id)
    header_size = struct.calcsize(fmt)
    data = struct.pack(fmt, command_id, sequence, len(session_id), session_id)
    return header_size, data

def pack_body(body):
    """
    包体
    """
    fmt = '!H%ds' % len(body)
    body_size = struct.calcsize(fmt)
    data = struct.pack(fmt, len(body), body)
    return body_size, data
    
def unpack(data): 
    """
    解包
    """
    command_id, sequence, session_id, data = unpack_header(data)
    body = unpack_body(data)
    return command_id, sequence, session_id, body

def unpack_size(data):
    """
    总长度
    """
    (size,) = struct.unpack('!i', data)
    return size

def unpack_header(data):
    """
    包头
    """
    (command_id,), data = struct.unpack('!I', data[:4]), data[4:]
    (sequence,), data = struct.unpack('!I', data[:4]), data[4:]
    (session_size,), data = struct.unpack('!B', data[:1]), data[1:]
    (session_id,), data = struct.unpack('!%ds' % (session_size), data[:session_size]), data[session_size:]
    return command_id, sequence, session_id, data

def unpack_body(data):
    """
    包体
    """
    (body_size,), data = struct.unpack('!H', data[:2]), data[2:]
    (body,) = struct.unpack('!%ds' % (body_size,), data)
    if isinstance(body, unicode):
        body.encode('utf-8')
    return body

 

你可能感兴趣的:(打包)