.cpp
bool NetworkManager::handle_data(TArray<uint8>& received_data, int _byte_cnt)
{
uint32_t handled_offset = 0;
while (handled_offset != _byte_cnt)
{
auto byte_cnt_left = _byte_cnt - handled_offset;
if (data_handle_record.head_rec_cnt < DataHandleRecord::Data_Head_Size)
{
if (byte_cnt_left + data_handle_record.head_rec_cnt < DataHandleRecord::Data_Head_Size)
{
memcpy(data_handle_record.get_head_write_pos(),
received_data.GetData(),
byte_cnt_left);
data_handle_record.head_rec_cnt += byte_cnt_left;
return true;
}
else
{
handled_offset += DataHandleRecord::Data_Head_Size - data_handle_record.head_rec_cnt;
memcpy(data_handle_record.get_head_write_pos(),
received_data.GetData(),
DataHandleRecord::Data_Head_Size - data_handle_record.head_rec_cnt);
data_handle_record.head_rec_cnt = DataHandleRecord::Data_Head_Size;
data_handle_record.update_body_buff_size();
continue;
}
}
if (byte_cnt_left < data_handle_record.pack_head.pack_len -
data_handle_record.body_rec_cnt)
{
data_handle_record.write_data_2_body(received_data.GetData(), byte_cnt_left);
handled_offset += byte_cnt_left;
}
else
{
auto len = data_handle_record.pack_head.pack_len -
data_handle_record.body_rec_cnt;
data_handle_record.write_data_2_body(received_data.GetData(), len);
handled_offset += len;
data_handle_record.reset();
}
}
return true;
}
.h
struct PackHead
{
uint8_t pack_id;
uint32_t pack_len;
};
struct DataHandleRecord
{
static const uint8_t Data_Head_Size = 5;
PackHead pack_head;
uint8_t head_rec_cnt = 0;
std::vector<uint8_t> body_buff;
uint32_t body_rec_cnt = 0;
void update_body_buff_size()
{
if (body_buff.size() < pack_head.pack_len)
{
body_buff.resize(pack_head.pack_len);
}
}
void reset()
{
head_rec_cnt = 0;
body_rec_cnt = 0;
}
void* get_head_write_pos()
{
return static_cast<void*>(&pack_head + head_rec_cnt);
}
void* write_data_2_body(const void* src, uint32_t len)
{
memcpy(&body_buff + len, src, len);
body_rec_cnt += len;
}
};
|