我在异步模式下使用 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/