提升asio和coroutine2的例子

时间:2016-08-17 02:23:23

标签: c++ boost boost-asio boost-coroutine boost-coroutine2

在阅读coroutine2的文档时,我发现了一个很好的snippet代码,展示了如何将其与asio一起使用

这里的参考是文档中的代码:

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";
    }
}

但是我找不到关于asio文档的工作示例,并且尝试在coliru上编译此代码段会给出与yield相关的编译器错误

您是否了解使用coroutine2的最小客户端/服务器实现,如上例所示?

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:4)

使用协同程序的示例Boost.Asio服务器为here

Boost.Coroutine文档中显示的示例缺少boost::asio::spawn用于创建可以作为异步处理程序传递的yield_context的部分。

通过关注#include中的<boost/asio/spawn.hpp>链,它似乎只包含Boost.Coroutine v1。