]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp03/tutorial/daytime3/server.cpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / libs / asio / example / cpp03 / tutorial / daytime3 / server.cpp
1 //
2 // server.cpp
3 // ~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
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)
9 //
10
11 #include <ctime>
12 #include <iostream>
13 #include <string>
14 #include <boost/bind.hpp>
15 #include <boost/shared_ptr.hpp>
16 #include <boost/enable_shared_from_this.hpp>
17 #include <boost/asio.hpp>
18
19 using boost::asio::ip::tcp;
20
21 std::string make_daytime_string()
22 {
23 using namespace std; // For time_t, time and ctime;
24 time_t now = time(0);
25 return ctime(&now);
26 }
27
28 class tcp_connection
29 : public boost::enable_shared_from_this<tcp_connection>
30 {
31 public:
32 typedef boost::shared_ptr<tcp_connection> pointer;
33
34 static pointer create(boost::asio::io_context& io_context)
35 {
36 return pointer(new tcp_connection(io_context));
37 }
38
39 tcp::socket& socket()
40 {
41 return socket_;
42 }
43
44 void start()
45 {
46 message_ = make_daytime_string();
47
48 boost::asio::async_write(socket_, boost::asio::buffer(message_),
49 boost::bind(&tcp_connection::handle_write, shared_from_this(),
50 boost::asio::placeholders::error,
51 boost::asio::placeholders::bytes_transferred));
52 }
53
54 private:
55 tcp_connection(boost::asio::io_context& io_context)
56 : socket_(io_context)
57 {
58 }
59
60 void handle_write(const boost::system::error_code& /*error*/,
61 size_t /*bytes_transferred*/)
62 {
63 }
64
65 tcp::socket socket_;
66 std::string message_;
67 };
68
69 class tcp_server
70 {
71 public:
72 tcp_server(boost::asio::io_context& io_context)
73 : acceptor_(io_context, tcp::endpoint(tcp::v4(), 13))
74 {
75 start_accept();
76 }
77
78 private:
79 void start_accept()
80 {
81 tcp_connection::pointer new_connection =
82 tcp_connection::create(acceptor_.get_executor().context());
83
84 acceptor_.async_accept(new_connection->socket(),
85 boost::bind(&tcp_server::handle_accept, this, new_connection,
86 boost::asio::placeholders::error));
87 }
88
89 void handle_accept(tcp_connection::pointer new_connection,
90 const boost::system::error_code& error)
91 {
92 if (!error)
93 {
94 new_connection->start();
95 }
96
97 start_accept();
98 }
99
100 tcp::acceptor acceptor_;
101 };
102
103 int main()
104 {
105 try
106 {
107 boost::asio::io_context io_context;
108 tcp_server server(io_context);
109 io_context.run();
110 }
111 catch (std::exception& e)
112 {
113 std::cerr << e.what() << std::endl;
114 }
115
116 return 0;
117 }