我正在从 boost::asio::ip::udp::socket
读取,如下所示:
using boost::asio::ip::udp;
// ...
char recv_buf[128];
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);
现在,这工作得很好,但我现在能够接收的最大字符数是127. 然而,我面临一个问题,因为我需要接受一些长度可能变化很大的数据输入(例如,长度不明确且带有前缀标头)。解决这个问题的方法是动态扩展缓冲区,就像向量一样。是否可以创建一个动态扩展的 boost::asio::buffer 来接受(理论上)无限量的输入并将其存储在容器中?
I'm reading from a boost::asio::ip::udp::socket
like this:
using boost::asio::ip::udp;
// ...
char recv_buf[128];
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);
Now, this works perfectly fine, but the maximum amount of characters that I am able to recieve is now 127. However I am facing a problem because I need to accept some data input of which the length can greatly vary (and is not of well-defined length with prefixed headers, for example). A solution to this would be a dynamically expanding buffer, like a vector. Is it possible to create a dynamically expanding boost::asio::buffer
to accept (theoretical) infite amounts of input and store it in a container?
发布评论
评论(4)
UDP 数据报大小变化不大:它永远不会大于 65535,离开8 字节标头后可容纳 65,527 字节数据。
UDP datagram size does not vary all that greatly: it will never be greater than 65535, leaving room for 65,527 bytes of data after the 8-byte header.
Boost 1.66.0 添加了
dynamic_buffer
,它可以调整对std::string
或std::vector
的引用:Boost 1.66.0 added
dynamic_buffer
which can adapt a reference tostd::string
orstd::vector<CharType>
:如果您使用较小的缓冲区,您可以通过 *BufferSequences 概念轻松地将它们链接在一起。例如,您可以传入 MutableBufferSequence
接受来自 read(2) 调用的数据或传递 ConstBufferSequence 用于您要写出(2) 的缓冲区列表。也就是说,我倾向于建议在每个方向使用单个缓冲区,因为它可以简化代码(尽管这并不总是可行)。
If you use smaller buffers, you can easily chain them together via the *BufferSequences concepts. For example, you can pass in a MutableBufferSequence
to accept data from a read(2) call or pass a ConstBufferSequence for a list of buffers that you are going to write(2) out. That said, I tend to recommend using a single buffer in each direction because it tends to simplify code (though that's not always possible).
似乎没有任何动态调整大小的规定。不存在也是有道理的。考虑一下会发生什么:
因此,动态大小的可用缓冲区是没有意义的。正如 Cubbi 指出的,无论如何,UDP 数据报的最大大小都较小,因此只需将缓冲区设置为与系统中最大的有效消息一样大即可。
There does not appear to be any provision for dynamic sizing. And it makes sense that there would not be. Think about what would have to happen:
So it does not make sense for there to be a dynamically-sized buffer available. As Cubbi points out, UDP datagrams have a smallish maximum size anyway, so just make your buffer as large as the largest valid message in your system and be done with it.