从boost asio streambuf读取会将字节保持在缓冲区中
Reading from boost asio streambuf keeps bytes in buffer
我在读取boost asio的流时遇到问题。async_read_until的第一次调用给了我460个字节的传输(我用wireshark检查过)。之后,我使用用streambuf指针初始化的istream,将std::copy_n与istreambuf_editor一起使用。这很好,std::copy_n的目标将请求保持到分隔符序列。
奇怪的事情发生在下一次调用async_read_until之后。最后一个字符似乎没有从streambuf中读取,所以下一个处理程序调用给我的比请求的实际大小多一个字节。
将istream与asio的streambuf一起使用有任何限制吗?
除了注释之外,这里还有一个小演示程序,展示了与asio::streambuf
交互的两种方式。
一种方法将streambuf封装在i/o流中,另一种方法使用prepare/commit和data/consume的直接访问。
#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <algorithm>
#include <memory>
namespace asio = boost::asio;
void direct_insert(asio::streambuf& sb, std::string const& data)
{
auto size = data.size();
auto buffer = sb.prepare(size);
std::copy(begin(data), end(data), asio::buffer_cast<char*>(buffer));
sb.commit(size);
}
void stream_insert(asio::streambuf& sb, std::string const& data)
{
std::ostream strm(std::addressof(sb));
strm << data;
}
std::string extract_istream(asio::streambuf& sb)
{
std::istream is(std::addressof(sb));
std::string line;
std::getline(is, line);
return line;
}
std::string extract_direct(asio::streambuf& sb)
{
auto buffer = sb.data();
auto first = asio::buffer_cast<const char*>(buffer);
auto bufsiz = asio::buffer_size(buffer);
auto last = first + bufsiz;
auto nlpos = std::find(first, last, 'n');
auto result = std::string(first, nlpos);
auto to_consume = std::min(std::size_t(std::distance(first, nlpos) + 1), bufsiz);
sb.consume(to_consume);
return result;
}
int main()
{
asio::streambuf buf;
direct_insert(buf, "The cat sat on the matn");
stream_insert(buf, "The cat sat on the matn");
auto s1 = extract_direct(buf);
auto s2 = extract_istream(buf);
std::cout << s1 << "n" << s2 << "n";
}
相关文章:
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 找到一种有效的方法,在 2 个巨大的缓冲区上执行 MAX,每字节字节
- 从原始字节解码协议缓冲区(以 C++为单位)
- 如果我向一个12字节的缓冲区写入的字节数少于12,会发生什么情况
- 将constexpr字节数组与缓冲区的一部分(指向数据的指针)进行比较
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- Fread C++ in C#.我知道我需要字节缓冲区,但并不完全在那里
- 如何通过1024字节缓冲区和强力冲洗在插座连接上发送6个字符的C弦
- 将缓冲区与 N 字节边界对齐,而不是 2N 字节边界?
- std::字符串与字节缓冲区(C++的差异)
- 删除字节数组 : Qt 缓冲区之间的空字符 (\x00)
- 浅拷贝到协议缓冲区的字节字段中
- InternetReadFile 填充缓冲区,但返回零字节读取
- 平面缓冲区:访问冲突:字节序标量
- 缓冲区视图中的字节偏移量大于字节长度
- 将数组与传入的字节*缓冲区进行比较的最快方法
- 在内存(C 和/或 C++)中创建和管理字节缓冲区,该缓冲区可以根据需要自动调整大小
- 高效生成字节缓冲区,而不会破坏严格的混叠
- 如何在 Poco C++ 中复制缓冲区字节块
- DirectX 11追加缓冲区字节宽度