asio: Add example to use timer to achieve delayed response

This commit is contained in:
Tatsuhiro Tsujikawa 2015-03-06 01:04:46 +09:00
parent 05b8d8c5b7
commit 42c174e803
1 changed files with 24 additions and 4 deletions

View File

@ -64,22 +64,42 @@ int main(int argc, char *argv[]) {
server.handle("/", [](const request &req, const response &res) { server.handle("/", [](const request &req, const response &res) {
res.write_head(200, {{"foo", {"bar"}}}); res.write_head(200, {{"foo", {"bar"}}});
res.end("hello, world"); res.end("hello, world\n");
}); });
server.handle("/secret/", [](const request &req, const response &res) { server.handle("/secret/", [](const request &req, const response &res) {
res.write_head(200); res.write_head(200);
res.end("under construction!"); res.end("under construction!\n");
}); });
server.handle("/push", [](const request &req, const response &res) { server.handle("/push", [](const request &req, const response &res) {
boost::system::error_code ec; boost::system::error_code ec;
auto push = res.push(ec, "GET", "/push/1"); auto push = res.push(ec, "GET", "/push/1");
if (!ec) { if (!ec) {
push->write_head(200); push->write_head(200);
push->end("server push FTW!"); push->end("server push FTW!\n");
} }
res.write_head(200); 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<boost::asio::deadline_timer>(
res.io_service(), boost::posix_time::seconds(3));
auto closed = std::make_shared<bool>();
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); server.listen("*", port);