]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp11/buffers/reference_counted.cpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / libs / asio / example / cpp11 / buffers / reference_counted.cpp
1 //
2 // reference_counted.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 <boost/asio.hpp>
12 #include <iostream>
13 #include <memory>
14 #include <utility>
15 #include <vector>
16
17 using boost::asio::ip::tcp;
18
19 // A reference-counted non-modifiable buffer class.
20 class shared_const_buffer
21 {
22 public:
23 // Construct from a std::string.
24 explicit shared_const_buffer(const std::string& data)
25 : data_(new std::vector<char>(data.begin(), data.end())),
26 buffer_(boost::asio::buffer(*data_))
27 {
28 }
29
30 // Implement the ConstBufferSequence requirements.
31 typedef boost::asio::const_buffer value_type;
32 typedef const boost::asio::const_buffer* const_iterator;
33 const boost::asio::const_buffer* begin() const { return &buffer_; }
34 const boost::asio::const_buffer* end() const { return &buffer_ + 1; }
35
36 private:
37 std::shared_ptr<std::vector<char> > data_;
38 boost::asio::const_buffer buffer_;
39 };
40
41 class session
42 : public std::enable_shared_from_this<session>
43 {
44 public:
45 session(tcp::socket socket)
46 : socket_(std::move(socket))
47 {
48 }
49
50 void start()
51 {
52 do_write();
53 }
54
55 private:
56 void do_write()
57 {
58 std::time_t now = std::time(0);
59 shared_const_buffer buffer(std::ctime(&now));
60
61 auto self(shared_from_this());
62 boost::asio::async_write(socket_, buffer,
63 [this, self](boost::system::error_code /*ec*/, std::size_t /*length*/)
64 {
65 });
66 }
67
68 // The socket used to communicate with the client.
69 tcp::socket socket_;
70 };
71
72 class server
73 {
74 public:
75 server(boost::asio::io_context& io_context, short port)
76 : acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
77 {
78 do_accept();
79 }
80
81 private:
82 void do_accept()
83 {
84 acceptor_.async_accept(
85 [this](boost::system::error_code ec, tcp::socket socket)
86 {
87 if (!ec)
88 {
89 std::make_shared<session>(std::move(socket))->start();
90 }
91
92 do_accept();
93 });
94 }
95
96 tcp::acceptor acceptor_;
97 };
98
99 int main(int argc, char* argv[])
100 {
101 try
102 {
103 if (argc != 2)
104 {
105 std::cerr << "Usage: reference_counted <port>\n";
106 return 1;
107 }
108
109 boost::asio::io_context io_context;
110
111 server s(io_context, std::atoi(argv[1]));
112
113 io_context.run();
114 }
115 catch (std::exception& e)
116 {
117 std::cerr << "Exception: " << e.what() << "\n";
118 }
119
120 return 0;
121 }