提升asio和协同程序2示例

boost asio and coroutine2 example

本文关键字:程序 示例 asio 提升      更新时间:2023-10-16

在阅读coroutine2的文档时,我发现了一段很好的代码片段,展示了如何将其与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的最小客户端/服务器实现,如上面的示例所示?

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

这里给出了一个使用协程的基于Boost.Asio的服务器示例。

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

通过在<boost/asio/spawn.hpp>中遵循#include链,它似乎只包括Boost.Coroutine v1。