简体   繁体   中英

boost asio: async data reading

i know that this might be a generally stupid question, but is there a way to implement multistage async data reading in tcp where: a) we read first four bytes - where bytes 3&4 correspond to size of remaining packet b) we read the remaining packet (data) based on its finite size from step a.

I'm thinking about implementation using async_read. Something like this:

    char hd_buf[3];

boost::asio::async_read(
    conn->getNetSocket(),
    boost::asio::buffer(hd_buf, 3),
    boost::bind(&TCPServer::handleHeaderRead, this, boost::asio::placeholders::error));

auto dt_sz = &hd_buf[2] + &hd_buf[3]; //nvm this part, it exists in handleHeaderRead

char* dt_buf = new dt_buf[dt_sz];

boost::asio::async_read(
    conn->getNetSocket(),
    boost::asio::buffer(dt_buf, dt_sz),
    boost::bind(&TCPServer::handleDataRead, this, boost::asio::placeholders::error));

Am i in general correct with such implementation road?

Yes, most network protocoles store the dynamic size of the data to transfer in a fixed size field which comes before the data, for example :

[ size ][  data...  ]
 4bytes  `size`bytes

In general headers have fixed length, and the data length in within the header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM