C++ C语言Socket库Libevent的粘包处理

void MDVRConnectClient::on_read(struct bufferevent *bev, void *user_data)
{
    //获取输入缓冲区中的数据(数据未移走)
    struct evbuffer *input = bufferevent_get_input(bev);
    size_t content_size = evbuffer_get_length(input);
    if (content_size > 0)
    {
        uint8_t read_buffer[content_size];

        //读取数据
        bufferevent_read(bev, read_buffer, content_size);

        if (read_buffer[7] != FUNCTION_CODE_REAL_TIME_DATA && read_buffer[7] != 0xa0)
        {
            CommonUtil::show_hex_string("on_read: ", read_buffer, content_size);
        }

        //处理粘包
        uint8_t full_packet_data[content_size];
        int message_flag_count = 0;
        int full_packet_len = 0;
        for (int i = 0; i < content_size; i++)
        {

            if (full_packet_len == 0 && read_buffer[i] != MESSAGE_FLAG)
            {
                CommonUtil::show_text("first byte not 7e");
                continue;
            }

            full_packet_data[full_packet_len] = read_buffer[i];
            full_packet_len++;
            if (read_buffer[i] != MESSAGE_FLAG)
            {
                continue;
            }

            if (++message_flag_count % 2 == 0)
            {
                //完整消息
                MDVRMessageProcessor::process(bev, full_packet_data, full_packet_len);

                //下一包
                full_packet_len = 0;
            }
        }
    }
    else
    {
        printf("on_read size 0");
    }
}

 

你可能感兴趣的:(C++)