编程语言
首页 > 编程语言> > C/C++ 协议解析通用流转包方法不怕连包

C/C++ 协议解析通用流转包方法不怕连包

作者:互联网

一、流程图

二、详细代码 

//begin解析数据包
static uint8_t parse_packet_buf[20480];
static int16_t parse_packet_buf_index = 0;
static uint8_t resolver_num_packets = 0;
static void add_parse_packet_buf(uint8_t* data, uint16_t len)
{
	if(len<(20480-parse_packet_buf_index))
	{
		memcpy(&parse_packet_buf[parse_packet_buf_index], data, len);
		parse_packet_buf_index+=len;
	}
}

static void delete_parse_packet_buf(uint16_t len)
{
	memcpy(parse_packet_buf, &parse_packet_buf[len], parse_packet_buf_index-len);
  parse_packet_buf_index-=len;
}
static uint16_t resolver_delete(uint8_t* buff)
{
  int16_t byte_count = 0;
  int16_t data_len = 0;
  uint8_t check_sum = 0;
  uint8_t recv_checksum = 0;
  if(parse_packet_buf_index<=5)
  {
    return byte_count;
  }
  if ((buff[0] == 0xAA) && (buff[1] == 0x55))
  {
    data_len = (buff[3] << 8) + buff[4];
    if ((data_len != 0) && (data_len < 1024))
    {
      recv_checksum = get_checksum(&buff[5], data_len);
      check_sum = buff[2];  
      byte_count = data_len + 5;
      if (recv_checksum == check_sum)
      {
		  resolver_num_packets++;
          printf("check succes\r\n");
      }
      else
      {
        //CheckSum错误
        //滑动丢弃无用字节
        byte_count = 1;
        printf("check err\r\n");
      }
    }
    else
    {
        //滑动丢弃无用字节
        byte_count = 1;
    }
  }
  return byte_count;
}

static uint8_t parse_packet(uint8_t* data, uint16_t len)
{
  uint16_t delete_len = 0;
  resolver_num_packets = 0;
  add_parse_packet_buf(data,len);
	
  while(1)
  {
    delete_len = resolver_delete(parse_packet_buf);
    if(delete_len == 0)
    {
      break;
    }
    else
    {
      delete_parse_packet_buf(delete_len);
    }
  }
  return resolver_num_packets;
}

//end解析数据包

标签:流转,packet,uint8,parse,static,C++,len,buf,连包
来源: https://blog.csdn.net/g313105910/article/details/120859508