从boost asio streambuf读取缓冲区

时间:2017-10-23 09:08:34

标签: c++ boost boost-asio

我从提升asio&#s流中读取时遇到问题。第一次调用async_read_until给我转移了460个字节(我用wireshark检查了它)。之后我使用一个用streambuf指针初始化的istream来使用std :: copy_n和一个istreambuf_iterator。这工作正常,std :: copy_n的目标将请求保持到分隔符序列。

奇怪的事情发生在下一次调用async_read_until之后。看起来最后一个字符没有从streambuf中读取,所以下一个处理程序调用给我比请求的实际大小多一个字节。

使用istream和asio' streambuf有什么限制吗?

1 个答案:

答案 0 :(得分:4)

除了评论之外,还有一个小型演示程序,它显示了与asio::streambuf交互的两种方式。

一种方式将streambuf包装在i / o流中,另一种方式使用直接访问准备/提交和数据/消费。

#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 mat\n");
    stream_insert(buf, "The cat sat on the mat\n");

    auto s1 = extract_direct(buf);
    auto s2 = extract_istream(buf);

    std::cout << s1 << "\n" << s2 << "\n";
}