思路:
将发送的数据按照长度和body的方式一次放入一个大的buffer中,4个字节存放body长度,后面存放报文,依次放入数据。
后续如果想要存储复杂类型,可以拓展头部信息,比如数据类型等
#include <stdio.h>
#include <stdint.h>
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <string.h>
#define MSG_END 0xFFFFFFFF
using msg_t = std::vector<char>;
std::vector<msg_t> deserialize(msg_t msg) {
std::vector<msg_t> msgs;
uint32_t curr_index = 0;
do {
uint32_t length = 0;
//memcpy(&length, + curr_index, 4);
for (size_t i = 0; i < 4; i++) {
((char*)&length)[i] = msg[curr_index + i];
}
if (length == MSG_END) {
break;
}
curr_index += 4;
msgs.emplace_back(msg_t{ msg.begin() + curr_index, msg.begin() + curr_index + length });
//std::cout << "sub_msg->msg:" << sub_msg->msg << std::endl;
curr_index += length;
} while (1);
return msgs;
}
msg_t serialize(std::vector<msg_t>& msgs) {
uint32_t length = 0;
uint32_t curr_index = 0;
for (auto msg : msgs) {
length += msg.size();
}
length += (msgs.size() + 1) * 4;
msg_t ret_msg(length, 0);
for (auto msg : msgs) {
uint32_t msg_size = msg.size();
for (size_t i = 0; i < 4; i++) {
msg[curr_index+i] = ((char*)&msg_size)[i];
}
curr_index += 4;
std::copy(msg.begin(), msg.end(), ret_msg.begin() + curr_index);
curr_index += msg.size();
}
msg_t end(4, 0xff);
std::copy(end.begin(), end.begin(), ret_msg.begin() + curr_index);
return ret_msg;
}
int main() {
msg_t str1(10, 'a');
msg_t str2(20, 'b');
msg_t str3(5, 'c');
std::vector<msg_t> msgs{ str1,str2,str3 };
auto test_msg = serialize(msgs);
auto test_msgs = deserialize(test_msg);
for (auto s : test_msgs) {
for (auto c : s) {
printf("%c", c);
}
std::cout << std::endl;
}
return 0;
}