c++ - 使用 boost::asio 丢弃数据

标签 c++ boost boost-asio

我在异步模式下使用 boost::asio,我想跳过/丢弃/删除通过 TCP 发送给我的消息。我想这样做是因为我已经阅读了消息的标题,并且我知道我对此不感兴趣。消息可能很大,所以我宁愿不为它分配空间,甚至最好不要将它传输到用户空间。

我看到了 boost::asio::null_buffers,但它似乎不适用于此处(参见 https://svn.boost.org/trac/boost/ticket/3627)。

最佳答案

据我所知,BSD 套接字接口(interface)没有提供此功能。您总是必须读入缓冲区。现在,为了不分配巨大的缓冲区,您可以做的是在循环中读入较小的缓冲区。像这样:

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));
}

这还没有通过编译器,所以可能会有愚蠢的拼写错误,但它应该说明了这一点。

关于c++ - 使用 boost::asio 丢弃数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7167300/

相关文章:

c++ - boost ASIO async_write "Vector iterator not dereferencable"

c++ - boost::container::string 的内存是否连续?

c++ - 与慢消费者异步发送

c++ - 如何从多个静态库中创建一个静态库?

c++ - 无法将字符串参数传递给派生类成员函数 C++

c++ - 如何使用 boost 将计时器设置为 future 2 秒?

c++ - 从另一个线程恢复 asio 协程

c++ - 将 asio read_some 转换为异步版本

java - 类似Java的JSci的C++统计包

c++ - 如何强制从重写方法中调用重写方法基础方法?