]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp11/spawn/echo_server.cpp
350304e63edc934c046639a0e74131d40bb1c24b
5 // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
11 #include <boost/asio/io_context.hpp>
12 #include <boost/asio/ip/tcp.hpp>
13 #include <boost/asio/spawn.hpp>
14 #include <boost/asio/steady_timer.hpp>
15 #include <boost/asio/write.hpp>
19 using boost::asio::ip::tcp
;
21 class session
: public std::enable_shared_from_this
<session
>
24 explicit session(tcp::socket socket
)
25 : socket_(std::move(socket
)),
26 timer_(socket_
.get_io_context()),
27 strand_(socket_
.get_io_context())
33 auto self(shared_from_this());
34 boost::asio::spawn(strand_
,
35 [this, self
](boost::asio::yield_context yield
)
42 timer_
.expires_from_now(std::chrono::seconds(10));
43 std::size_t n
= socket_
.async_read_some(boost::asio::buffer(data
), yield
);
44 boost::asio::async_write(socket_
, boost::asio::buffer(data
, n
), yield
);
47 catch (std::exception
& e
)
54 boost::asio::spawn(strand_
,
55 [this, self
](boost::asio::yield_context yield
)
57 while (socket_
.is_open())
59 boost::system::error_code ignored_ec
;
60 timer_
.async_wait(yield
[ignored_ec
]);
61 if (timer_
.expires_from_now() <= std::chrono::seconds(0))
69 boost::asio::steady_timer timer_
;
70 boost::asio::io_context::strand strand_
;
73 int main(int argc
, char* argv
[])
79 std::cerr
<< "Usage: echo_server <port>\n";
83 boost::asio::io_context io_context
;
85 boost::asio::spawn(io_context
,
86 [&](boost::asio::yield_context yield
)
88 tcp::acceptor
acceptor(io_context
,
89 tcp::endpoint(tcp::v4(), std::atoi(argv
[1])));
93 boost::system::error_code ec
;
94 tcp::socket
socket(io_context
);
95 acceptor
.async_accept(socket
, yield
[ec
]);
96 if (!ec
) std::make_shared
<session
>(std::move(socket
))->go();
102 catch (std::exception
& e
)
104 std::cerr
<< "Exception: " << e
.what() << "\n";