[英]How to read a packet in boost::asio
how do i read a packet in boost::asio for example 0x01, current code i have only reads texts: 我如何在boost :: asio中读取数据包,例如0x01,当前代码我只读取文本:
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变量分配缓冲区,而不是使用从套接字读取的值
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 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. 这样,当asio异步调用您的读取处理程序(
Client::handleRead
)时,它将已将该缓冲区的内容更新为所接收的内容。
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. Asio不会将缓冲区填充超过您在
boost::asio::buffer(ptr, size)
指定的boost::asio::buffer(ptr, size)
,因此,如果您需要32位整数,则将指针传递给size = 4个字节的数组开头,然后在调用读取处理程序时将其转换为32位int类型(可能是stdint.h
uint32_t
)。
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. 通常,当您不需要整个32位整数时,可以通过传递16位或8位来节省大量内存。
uint8_t
and uint16_t
will let you do this without having to worry about whether your architecture's int
is not 32 bits. uint8_t
和uint16_t
可以让您执行此操作,而不必担心您的体系结构的int
是否不是32位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.