如何通过asio null_buffers优化UDP套接字实现长尾词效果?
- 内容介绍
- 文章标签
- 相关推荐
本文共计317个文字,预计阅读时间需要2分钟。
我想使用Boost ASIO库异步接收来自UDP套接字的 数据。我不想在使用async_receive_from接收数据时使用固定长度的缓冲区。以下是如何使用boost::asio::null_buffers来限定接收的数据包大小:
cpp#include #include
int main() { try { boost::asio::io_context io_context; boost::asio::ip::udp::socket socket(io_context, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 12345));
// 创建null_buffers来限定接收的数据包大小 boost::asio::null_buffers buffer;
// 异步接收数据 socket.async_receive_from(buffer, boost::asio::ip::udp::endpoint(), [](const boost::system::error_code& error, std::size_t length) { if (!error) { std::cout << Received data: <
// 运行io_context处理异步操作 io_context.run();
} catch (std::exception& e) { std::cerr << Exception: < return 0;} 以下代码是我如何使用boost asio :: null_buffers来确定传入的数据包大小并相应地创建缓冲区. socket.async_receive_from(boost::asio::null_buffers(),
remote_endpoint,
[&](boost::system::error_code ec, std::size_t bytes) {
unsigned int readbytes = socket.available();
if (readbytes > buffer_size) {
//reallocate buffer
}
std::size_t recvbytes = socket.receive_from(
boost::asio::buffer(buffer, buffer_size), remote_endpoint, 0, error);
一切都按预期工作,但是,我想知道boost null_buffer是否分配一个内部缓冲区来保存收到的UDP数据包的副本,并在调用socket.receive_from()时复制到给定的缓冲区. 另外,我想知道在使用UDP套接字时使用null_buffer对性能和内存使用情况有何影响. 此外,Boost 1.66.0有the new interface,其中null_buffers已过时,并且使用套接字上的async_wait操作可以实现反应堆式集成: 参见例如这里的文档www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/basic_socket/wait/overload1.html
本文共计317个文字,预计阅读时间需要2分钟。
我想使用Boost ASIO库异步接收来自UDP套接字的 数据。我不想在使用async_receive_from接收数据时使用固定长度的缓冲区。以下是如何使用boost::asio::null_buffers来限定接收的数据包大小:
cpp#include #include
int main() { try { boost::asio::io_context io_context; boost::asio::ip::udp::socket socket(io_context, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 12345));
// 创建null_buffers来限定接收的数据包大小 boost::asio::null_buffers buffer;
// 异步接收数据 socket.async_receive_from(buffer, boost::asio::ip::udp::endpoint(), [](const boost::system::error_code& error, std::size_t length) { if (!error) { std::cout << Received data: <
// 运行io_context处理异步操作 io_context.run();
} catch (std::exception& e) { std::cerr << Exception: < return 0;} 以下代码是我如何使用boost asio :: null_buffers来确定传入的数据包大小并相应地创建缓冲区. socket.async_receive_from(boost::asio::null_buffers(),
remote_endpoint,
[&](boost::system::error_code ec, std::size_t bytes) {
unsigned int readbytes = socket.available();
if (readbytes > buffer_size) {
//reallocate buffer
}
std::size_t recvbytes = socket.receive_from(
boost::asio::buffer(buffer, buffer_size), remote_endpoint, 0, error);
一切都按预期工作,但是,我想知道boost null_buffer是否分配一个内部缓冲区来保存收到的UDP数据包的副本,并在调用socket.receive_from()时复制到给定的缓冲区. 另外,我想知道在使用UDP套接字时使用null_buffer对性能和内存使用情况有何影响. 此外,Boost 1.66.0有the new interface,其中null_buffers已过时,并且使用套接字上的async_wait操作可以实现反应堆式集成: 参见例如这里的文档www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/basic_socket/wait/overload1.html

