简体   繁体   中英

boost asio and coroutine2 example

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?

AFAIK boost.asio仅支持boost.coroutine,而不支持boost.coroutine2

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM