From 42c174e80380d122d8167186b9d6d4d3a181c5fd Mon Sep 17 00:00:00 2001 From: Tatsuhiro Tsujikawa Date: Fri, 6 Mar 2015 01:04:46 +0900 Subject: [PATCH] asio: Add example to use timer to achieve delayed response --- examples/asio-sv.cc | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/examples/asio-sv.cc b/examples/asio-sv.cc index c880d0d6..6fc320c4 100644 --- a/examples/asio-sv.cc +++ b/examples/asio-sv.cc @@ -64,22 +64,42 @@ int main(int argc, char *argv[]) { server.handle("/", [](const request &req, const response &res) { res.write_head(200, {{"foo", {"bar"}}}); - res.end("hello, world"); + res.end("hello, world\n"); }); server.handle("/secret/", [](const request &req, const response &res) { res.write_head(200); - res.end("under construction!"); + res.end("under construction!\n"); }); server.handle("/push", [](const request &req, const response &res) { boost::system::error_code ec; auto push = res.push(ec, "GET", "/push/1"); if (!ec) { push->write_head(200); - push->end("server push FTW!"); + push->end("server push FTW!\n"); } res.write_head(200); - res.end("you'll receive server push!"); + res.end("you'll receive server push!\n"); + }); + server.handle("/delay", [](const request &req, const response &res) { + res.write_head(200); + + auto timer = std::make_shared( + res.io_service(), boost::posix_time::seconds(3)); + auto closed = std::make_shared(); + + res.on_close([timer, closed](uint32_t error_code) { + timer->cancel(); + *closed = true; + }); + + timer->async_wait([&res, closed](const boost::system::error_code &ec) { + if (ec || *closed) { + return; + } + + res.end("finally!\n"); + }); }); server.listen("*", port);