使用boost :: asio丢弃数据

mpm*_*mpm 7 c++ boost boost-asio

我在异步模式下使用boost :: asio,我想跳过/丢弃/丢弃通过TCP发送给我的消息.我想这样做,因为我已经阅读了该消息的标题,我知道这对我没有意义.消息可能很大,所以我宁愿不为它分配空间,更不要将它转移到用户空间.

我看到boost :: asio :: null_buffers但它似乎不适用于此(请参阅https://svn.boost.org/trac/boost/ticket/3627).

Arv*_*vid 7

据我所知,BSD套接字接口不提供此功能.你总是要读入一个缓冲区.现在,为了不分配大量缓冲区,您可以做的是在循环中读入较小的缓冲区.像这样的东西:

void skip_impl(tcp::socket& s, int n, boost::function<void(error_code const&)> h
    , char* buf, error_code const& ec, std::size_t bytes_transferred)
{
    assert(bytes_transferred <= n);
    n -= bytes_transferred;
    if (ec || n == 0) {
        delete[] buf;
        h(ec);
        return;
    }

    s.async_read_some(boost::asio::buffer(temp, std::min(4096, n))
        , boost::bind(&skip_impl, boost::ref(s), n, h, temp, _1, _2));
}

void async_skip_bytes(tcp::socket& s, int n, boost::function<void(error_code const&)> h)
{
    char* temp = new char[4096];
    s.async_read_some(boost::asio::buffer(temp, std::min(4096, n))
        , boost::bind(&skip_impl, boost::ref(s), n, h, temp, _1, _2));
}
Run Code Online (Sandbox Code Playgroud)

这还没有通过编译器传递,因此可能存在愚蠢的拼写错误,但它应该说明这一点.