Reputation: 4347
While reading the documentation of coroutine2
I found a nice snippet of code that shows how to use it with asio
For reference here's the code from the documentation:
void session(boost::asio::io_service& io_service){
// construct TCP-socket from io_service
boost::asio::ip::tcp::socket socket(io_service);
try{
for(;;){
// local data-buffer
char data[max_length];
boost::system::error_code ec;
// read asynchronous data from socket
// execution context will be suspended until
// some bytes are read from socket
std::size_t length=socket.async_read_some(
boost::asio::buffer(data),
boost::asio::yield[ec]);
if (ec==boost::asio::error::eof)
break; //connection closed cleanly by peer
else if(ec)
throw boost::system::system_error(ec); //some other error
// write some bytes asynchronously
boost::asio::async_write(
socket,
boost::asio::buffer(data,length),
boost::asio::yield[ec]);
if (ec==boost::asio::error::eof)
break; //connection closed cleanly by peer
else if(ec)
throw boost::system::system_error(ec); //some other error
}
} catch(std::exception const& e){
std::cerr<<"Exception: "<<e.what()<<"\n";
}
}
However I can't find a working example on the asio documentation, and trying to compile this snippet on coliru gives me compiler errors related to yield
Are you aware of a minimal client/server implementation that uses coroutine2
as showed in the example above?
Upvotes: 8
Views: 5332
Reputation: 29209
An example Boost.Asio-based server using coroutines is given here.
The example shown in the Boost.Coroutine documentation is missing the part where boost::asio::spawn
is used to create a yield_context
that can be passed as a asynchronous handler.
By following the #include
chain within <boost/asio/spawn.hpp>
, it seems to include Boost.Coroutine v1 only.
Upvotes: 4
Reputation: 2109
AFAIK boost.asio supports only boost.coroutine, not boost.coroutine2
Upvotes: 10