我在一个程序上工作,该程序发送不同大小的不同数据。我使用 8 字节的固定标头来编码大小,然后,我添加数据:
enum { header_length = 8 }; //const header length
我得到了大小(m_outbound_data 是一个 std::string == 一个序列化对象)
//give header length
std::ostringstream header_stream
header_stream << std::setw(header_length) //set a field padding for header
<< std::hex //set next val to hexadecimal
<< m_data_out.m_outbound_data.size(); //write size in hexa
m_data_out.m_outbound_header = header_stream.str(); //m_outbound_head == size in hexa in a std::string
//m_outbound_header = [ 8 byte size ]
//m_outbound_data = [ serialized data ]
//write all data in the std::vector and send it
std::vector<boost::asio::const_buffer> buffer;
buffer.push_back(boost::asio::buffer(m_data_out.m_outbound_header));
buffer.push_back(boost::asio::buffer(m_data_out.m_outbound_data));
而对于读取,您需要读取 2 次:第一次读取 8 个字节以获取大小,然后读取向量中的数据并反序列化为对象:
struct network_data_in {
char m_inbound_header[header_length]; //size of data to read
std::vector<char> m_inbound_data; // read data
};
我使用这个结构来获取数据,在 m_inbound_header 上调用 read 以先用大小填充缓冲区,然后在句柄中:
//get size of data
std::istringstream is(std::string(m_data_in.m_inbound_header, header_length));
std::size_t m_inbound_datasize = 0;
is >> std::hex >> m_inbound_datasize;
m_data_in.m_inbound_data.resize(m_inbound_datasize); //resize the vector
然后使用缓冲区上的 m_inbound_data 再次调用 read,此结果将准确读取发送的数据
在第二个 handle_read 中,您必须反序列化数据:
//extract data
std::string archive_data (&(m_data_in.m_inbound_data[0]),m_data_in.m_inbound_data.size());
std::istringstream archive_stream(archive_data);
boost::archive::text_iarchive archive(archive_stream);
archive >> t; //deserialize
希望对你有所帮助!