ipkn / crow

Crow is very fast and easy to use C++ micro web framework (inspired by Python Flask)
BSD 3-Clause "New" or "Revised" License
7.47k stars 888 forks source link

can i use async response using crow internal io_service like nodejs express? #300

Closed legokichi closed 6 years ago

legokichi commented 6 years ago

e.g.

CROW_ROUTE(app, "/foo")
([&app](const crow::request& req, crow::response& res){
    auto ios = app->server_.get_io_service();
    auto timer = boost::asio::deadline_timer{*ios};
    timer.expires_from_now(boost::posix_time::seconds(1));
    timer.async_wait([&res](auto ec){
        res.write("hello");
        res.end();
    });
});
legokichi commented 6 years ago

finaly i found it. thanks!

#include <boost/asio.hpp>
#include "crow_all.h"

auto main() -> int {
    namespace asio = boost::asio;
    crow::SimpleApp app;

    CROW_ROUTE(app, "/foo")
    ([](const crow::request& req, crow::response& res){
        auto timer = new boost::asio::deadline_timer{*(req.io_service)};
        timer->expires_from_now(boost::posix_time::seconds(10));
        std::cout << "before" << std::endl;
        timer->async_wait([=, &req, &res](auto ec){
            delete timer;
            std::cout << "after:" << std::endl;
            res.write("hi!");
            res.end();
        });
    });
    app.port(18080).run();
}