我正在编写一些基于 ASIO 的网络代码(独立的,没有提升)。我已经编写了一些具有按预期工作的同步工作流的测试代码。但是当我尝试异步(基本上用 asio::async_read_until
替换 asio::read_until
)时,永远不会调用完成处理程序:
auto receive = [&](auto self)
{
asio::async_read_until(socket, buf, '\n', [&](auto const& err, auto read)
{
std::string s;
std::istream is(&buf);
std::getline(is, s);
std::cout << "received: \"" << s << "\"\n\n";
if (socket.is_open())
self(self);
});
};
socket
是一个 tcp::socket
而 buf
是一个 asio::streambuf
。这是我的代码中唯一发生变化的部分,我不知道为什么这里没有调用处理程序。
完整代码如下:
#include <asio.hpp>
#include <thread>
#include <string>
#include <string_view>
#include <iostream>
using namespace asio::ip;
using namespace std::literals;
constexpr auto IP = "127.0.0.1"sv;
constexpr auto Service = "50000"sv;
constexpr unsigned short Port = 50000;
void server()
{
asio::io_context context;
std::thread t([&context] { context.run(); });
tcp::acceptor acceptor(context, tcp::endpoint(tcp::v4(), Port));
auto socket = acceptor.accept();
std::cout << "Server connected.\n";
asio::streambuf buf;
auto receive = [&](auto self)
{
asio::async_read_until(socket, buf, '\n', [&](auto const& err, auto read)
{
std::string s;
std::istream is(&buf);
std::getline(is, s);
std::cout << "received: \"" << s << "\"\n\n";
if (socket.is_open())
self(self);
});
};
receive(receive);;
while (socket.is_open())
std::this_thread::sleep_for(1s);
std::cout << "Server shutdown.\n";
context.stop();
t.join();
}
void client()
{
asio::io_context context;
std::thread t([&context] { context.run(); });
auto endpoints = tcp::resolver(context).resolve(IP, Service);
tcp::socket socket(context);
asio::connect(socket, endpoints);
std::cout << "Client connected.\n";
std::string msg;
asio::streambuf buf;
std::getline(std::cin, msg);
while (!msg.empty())
{
std::ostream os(&buf);
os << msg << "\n";
auto written = asio::write(socket, buf);
if (written != msg.size() + 1)
std::cout << "Couldn't send message.";
std::getline(std::cin, msg);
}
context.stop();
t.join();
}
int main()
{
std::thread t1(server);
std::thread t2(client);
t1.join();
t2.join();
return 0;
}
编辑
看起来没有异步操作对我有用。如果我也使接受器异步,则它的处理程序永远不会被调用(尽管客户端能够连接到套接字)。
这些是所做的更改(在 server()
函数内):
tcp::acceptor acceptor(context, tcp::endpoint(tcp::v4(), Port));
acceptor.async_accept([&](auto const& err, tcp::socket sock)
{
socket = std::move(sock);
cv.notify_one();
});
{
std::mutex m;
std::unique_lock lk(m);
cv.wait(lk);
}
我已经在 lambda 内部设置了一个断点,但它没有被触发。
最佳答案
第一个问题:run
在没有任何挂起的任务要执行时结束。在您的情况下, run
是在第一个异步任务启动之前启动的。 run
已完成,无法调用处理程序。解决方案?使用 work
对象,它可以防止 run
在没有任何任务时结束。
asio::io_context context;
asio::io_context::work work{context};
std::thread t([&context] { context.run(); });
因为 work
已被弃用,您可以使用 executor_work_guard
:
asio::executor_work_guard<decltype(context.get_executor())> work{context.get_executor()};
或者仅当您使用 c++17 时才使用更短的形式:
asio::executor_work_guard work{context.get_executor()};
但这种方法有一个问题,t.join
将永远等待。 work
必须被销毁,这样 run
才能结束。我们不能用局部变量实现这种行为。
但是使用智能指针我们可以做到:
std::unique_ptr< asio::io_context::work> work =
std::make_unique< asio::io_context::work>(context);
std::thread t([&context] { context.run(); });
... the rest code
context.stop();
work.reset();
t.join();
第二个问题在 lambda 中:
auto receive = [&](auto self)
{
asio::async_read_until(socket, buf, '\n', [&](auto const& err, auto read)
{ ^^^^
std::string s;
std::istream is(&buf);
std::getline(is, s);
std::cout << "received: \"" << s << "\"\n\n";
if (socket.is_open())
self(self);
});
};
您正在通过 [&]
引用捕获 self
,这是个坏主意,因为 self
在外部 lambda 中是局部的。因为 async-function 立即返回,self
被销毁并且在内部 lambda 中你有悬空引用。
试试这个:
[self,&socket,&buf](auto const& err, auto read)
关于c++ - 异步操作的 Asio 处理程序不会被调用,而它们的同步对应项可以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57627397/