I'm trying to write a function async_read_string_n
to asynchronously read a string of exactly n
bytes from a socket with Boost.Asio 1.78 (and GCC 11.2).
This is how I want to use the function async_read_string_n
:
void run() {
co_spawn (io_context_, [&]() -> awaitable<void> {
auto executor = io_context_.get_executor();
tcp::acceptor acceptor(executor, listen_endpoint_);
auto [ec, socket] = co_await acceptor.async_accept(as_tuple(use_awaitable));
co_spawn(executor, [&]() -> awaitable<void> {
auto [ec, header] = co_await async_read_string_n(socket, 6, as_tuple(use_awaitable));
std::cerr << "received string " << header << "\n";
co_return;
}
, detached);
co_return;
}
, detached);
}
Here is my attempt to write async_read_string_n
, following the advice in
- https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/reference/asynchronous_operations.html#boost_asio.reference.asynchronous_operations.automatic_deduction_of_initiating_function_return_type
- https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/overview/core/cpp20_coroutines.html#boost_asio.overview.core.cpp20_coroutines.error_handling
(I don't care about memory copying. This isn't supposed to be fast; it's supposed to have a nice API.)
template<class CompletionToken> auto async_read_string_n(tcp::socket& socket, int n, CompletionToken&& token) {
async_completion<CompletionToken, void(boost::system::error_code, std::string)> init(token);
asio::streambuf b;
asio::streambuf::mutable_buffers_type bufs = b.prepare(n);
auto [ec, bytes_transferred] = co_await asio::async_read(socket, bufs, asio::transfer_exactly(n), as_tuple(use_awaitable));
b.commit(n);
std::istream is(&b);
std::string s;
is >> s;
b.consume(n);
init.completion_handler(ec, s);
return init.result.get();
}
Edit
(I had a syntax error and I fixed it.) Here is the compiler error in async_read_string_n
which I'm stuck on:
GCC error:
error: 'co_await' cannot be used in a function with a deduced return type
How can I write the function async_read_string_n
?