我的消息格式与您的非常相似(16 位有效负载长度,8 位数据包 ID/类型,然后是我的有效负载)。我通过 3 阶段读取和用于处理不同事物的函数指针数组来完成它。我使用 boost::asio::async_read 一次读取已知数量。
这是我的代码的简化版本:
//call this to start reading a packet/message
void startRead(boost::asio::ip::tcp::socket &socket)
{
boost::uint8_t *header = new boost::uint8_t[3];
boost::asio::async_read(socket,boost::asio::buffer(header,3),
boost::bind(&handleReadHeader,&socket,header,
boost::asio::placeholders::bytes_transferred,boost::asio::placeholders::error));
}
void handleReadHeader(boost::asio::ip::tcp::socket *socket,
boost::uint8_t *header, size_t len, const boost::system::error_code& error)
{
if(error)
{
delete[] header;
handleReadError(error);
}
else
{
assert(len == 3);
boost::uint16_t payLoadLen = *((boost::uint16_t*)(header + 0));
boost::uint8_t type = *((boost::uint8_t*) (header + 2));
delete[] header;
//dont bother calling asio again if there is no payload
if(payLoadLen > 0)
{
boost::uint8_t *payLoad = new boost::uint8_t[payLoadLen];
boost::asio::async_read(*socket,boost::asio::buffer(payLoad,payLoadLen),
boost::bind(&handleReadBody,socket,
type,payLoad,payLoadLen,
boost::asio::placeholders::bytes_transferred,boost::asio::placeholders::error));
}
else handleReadBody(socket,type,0,0,0,boost::system::error_code());
}
}
void handleReadBody(ip::tcp::socket *socket,
boost::uint8_t type, boost::uint8_t *payLoad, boost::uint16_t len,
size_t readLen, const boost::system::error_code& error)
{
if(error)
{
delete[] payLoad;
handleReadError(error);
}
else
{
assert(len == readLen);
//passes the packet to the appropriate function for the type
//you could also use a switch statement or whatever
//to get the next packet you must call StartRead again
//personally I choose to do this from the actaul handler
//themselves
handlePacket(type,payLoad,len,error);
}
}