BOOST ASIO:如何通过 async_read_until 使用有限的缓冲区大小
我使用一个小缓冲区(例如 128 字节),并且我想对 TCP 连接上的大传入消息使用“async_read_until”(丢弃除分隔符之前的最后 128 字节之外的所有字节)。
这怎么能做到呢? ASIO 文档不太清楚当提供的缓冲区不够大时会发生什么。
这是我的读取初始化代码
typedef boost::shared_ptr<boost::asio::streambuf >streambuf_ptr;
streambuf_ptr inBuf(new boost::asio::streambuf (128));
boost::asio::async_read_until(*sock, *inBuf, "\r\n\r\n", boost::bind(my_read_handler, sock, inBuf, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
I use a small buffer (e.g. 128 bytes) and I want to use "async_read_until" with big incoming messages on the TCP connection (discarding all but last 128 bytes prior to the delimiter).
How can this be done? The ASIO docs are not very clear what happens when the provided buffer is not big enough.
Here is my code for the read initiazation
typedef boost::shared_ptr<boost::asio::streambuf >streambuf_ptr;
streambuf_ptr inBuf(new boost::asio::streambuf (128));
boost::asio::async_read_until(*sock, *inBuf, "\r\n\r\n", boost::bind(my_read_handler, sock, inBuf, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当提供的缓冲区不够大时,
async_read_until
会完全填充它,然后使用错误代码asio::error::not_found
调用读取处理程序,这意味着分隔符没有找到。此时,您可以
.consume()
缓冲区中的部分(或全部)数据并再次调用async_read_until
。对于 128 字节的缓冲区,可能很难保证当最终找到分隔符时,它恰好位于缓冲区中的最后一个位置(即使如此,对于四字节分隔符,您也只能找到最后一个分隔符)之前的 124 字节)。最好在not_found
错误处理程序中使用更大的缓冲区和buffer.consume(buffer.size()-128)
,以确保至少有 128 个字节随时免费。When the provided buffer is not big enough,
async_read_until
fills it in completely and then invokes the read handler with the error codeasio::error::not_found
, meaning that the delimiter was not found.At that point you can
.consume()
some (or all) data from the buffer and callasync_read_until
again. It may be difficult to guarantee, with a 128-byte buffer, that when the delimiter is finally found, it is in the exact last position in the buffer (and even then, with a four-byte delimiter, you will only have the last 124 bytes prior to it). It may be best to use a larger buffer andbuffer.consume(buffer.size()-128)
in thenot_found
error handler, to make sure there's at least 128 bytes free at all time.