【发布时间】:2021-09-09 09:12:09
【问题描述】:
一开始调用async_write可以通过TCP成功发送数据,但是再次调用async_write就出错了。
这是code snippet:
#include <algorithm>
#include <array>
#include <boost/asio.hpp>
#include <boost/range.hpp>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
const std::size_t buf_size = 500*1024;
const int test_cycles = 1.024e5;
namespace asio = boost::asio;
int main()
{
std::vector<char> send_data(buf_size);
std::vector<char> recv_buf(buf_size);
asio::io_service ios;
asio::ip::tcp::socket socket1(ios);
asio::ip::tcp::socket socket2(ios);
asio::ip::tcp::acceptor acceptor(ios, {asio::ip::tcp::v4(), 55557});
socket1.connect({asio::ip::address_v4::loopback(), 55557});
acceptor.accept(socket2);
for (std::size_t i = 0; i < 1; ++i)
{
auto start = std::chrono::steady_clock::now();
for(int j=0; j < test_cycles; ++j)
{
size_t written_bytes = 0;
auto to_send_data = send_data;
asio::async_write(socket1,
asio::dynamic_buffer(send_data),
[&](auto ec, auto n)
{
if(!ec)
{
std::cout << "successfully sent " << n << std::endl;
}
else
{
std::cout << ec.message() << std::endl;
}
if(0==n)
{
std::cout << "send error" << std::endl;
}
written_bytes = n;
});
asio::async_read(socket2, asio::buffer(recv_buf),
[&](auto ec, auto n)
{
if(!ec)
{
//std::cout << "received " << n << std::endl;
}
else
{
std::cout << ec.message() << std::endl;
}
if(0==n)
{
std::cout << "received error" << std::endl;
}
if(written_bytes != n)
{
std::cout << "received is not same with the sent" << std::endl;
}
});
ios.run();
ios.reset();
}
auto end = std::chrono::steady_clock::now();
std::chrono::duration<float> elapsed = end - start;
std::cout << elapsed.count() << " seconds\n";
std::cout << (buf_size * test_cycles / elapsed.count() / 1024 / 1024/ 1024) << " GB/s\n";
}
}
这是输出:
successfully sent 512000
successfully sent 0
send error
一些提示
我找到了一个workaround方法,程序运行良好。下面是相关代码sn-p:
auto to_send_data = send_data;
asio::async_write(socket1,
asio::dynamic_buffer(to_send_data),
为什么前面的代码sn-p会出错?
更新:
-
我尝试通过 VsCode IDE 在 STD::vector::resize() 的实现中设置断点(我在 Ubuntu 上做了这个测试。),但断点确实不起作用(即断点是灰色的。) .我可以保证二进制程序是作为调试模式构建的。我也尝试通过 GDB 设置断点,但是 GDB 输出“Function "std::vector::resize" not defined。”
-
我在前面提到的operator()的实现中设置了断点,我发现default确实never被触发了,也就是说start总是1。
【问题讨论】:
标签: php boost tcp boost-asio ipv4