How to read a packet in boost::asio
how do i read a pac开发者_开发问答ket in boost::asio for example 0x01, current code i have only reads texts:
m_socket.async_read_some(boost::asio::buffer(buffer),
strand.wrap(boost::bind(&Client::handleRead, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
thanks
Hi you can assign buffer with your int variable and than use value you read from socket
int m_hdr_size = 0; // this var must be not local
boost::asio::async_read_some(
boost::asio::buffer(reinterpret_cast<char*>(&m_hdr_size), size_t(4))...
if i understand your question. Just set variable and it size to buffer
http://think-async.com/Asio/boost_asio_1_3_1/doc/html/boost_asio/reference/buffer.html
Doubt you need this answer a year later, but for the general public:
In your code, buffer is being passed by reference. This is so that when asio asynchronously calls your read handler (Client::handleRead
), it will have updated the contents of that buffer to whatever it received.
A buffer is simply an array with a specified size. Asio will not fill the buffer past the size you specify in boost::asio::buffer(ptr, size)
, so if you need a 32 bit integer, then pass it a pointer to the beginning of an array with size = 4 bytes, and then cast it to a 32-bit int type (probably uint32_t
from stdint.h
) when it calls the read handler.
You can usually save a good chunk of memory by passing 16 bits or 8 bits when you don't need an entire 32 bit integer. uint8_t
and uint16_t
will let you do this without having to worry about whether your architecture's int
is not 32 bits.
精彩评论