]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp03/buffers/reference_counted.cpp
2 // reference_counted.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2016 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.hpp>
12 #include <boost/bind.hpp>
13 #include <boost/enable_shared_from_this.hpp>
14 #include <boost/shared_ptr.hpp>
18 using boost::asio::ip::tcp
;
20 // A reference-counted non-modifiable buffer class.
21 class shared_const_buffer
24 // Construct from a std::string.
25 explicit shared_const_buffer(const std::string
& data
)
26 : data_(new std::vector
<char>(data
.begin(), data
.end())),
27 buffer_(boost::asio::buffer(*data_
))
31 // Implement the ConstBufferSequence requirements.
32 typedef boost::asio::const_buffer value_type
;
33 typedef const boost::asio::const_buffer
* const_iterator
;
34 const boost::asio::const_buffer
* begin() const { return &buffer_
; }
35 const boost::asio::const_buffer
* end() const { return &buffer_
+ 1; }
38 boost::shared_ptr
<std::vector
<char> > data_
;
39 boost::asio::const_buffer buffer_
;
43 : public boost::enable_shared_from_this
<session
>
46 session(boost::asio::io_service
& io_service
)
58 using namespace std
; // For time_t, time and ctime.
60 shared_const_buffer
buffer(ctime(&now
));
61 boost::asio::async_write(socket_
, buffer
,
62 boost::bind(&session::handle_write
, shared_from_this()));
70 // The socket used to communicate with the client.
74 typedef boost::shared_ptr
<session
> session_ptr
;
79 server(boost::asio::io_service
& io_service
, short port
)
80 : io_service_(io_service
),
81 acceptor_(io_service
, tcp::endpoint(tcp::v4(), port
))
83 session_ptr
new_session(new session(io_service_
));
84 acceptor_
.async_accept(new_session
->socket(),
85 boost::bind(&server::handle_accept
, this, new_session
,
86 boost::asio::placeholders::error
));
89 void handle_accept(session_ptr new_session
,
90 const boost::system::error_code
& error
)
97 new_session
.reset(new session(io_service_
));
98 acceptor_
.async_accept(new_session
->socket(),
99 boost::bind(&server::handle_accept
, this, new_session
,
100 boost::asio::placeholders::error
));
104 boost::asio::io_service
& io_service_
;
105 tcp::acceptor acceptor_
;
108 int main(int argc
, char* argv
[])
114 std::cerr
<< "Usage: reference_counted <port>\n";
118 boost::asio::io_service io_service
;
120 using namespace std
; // For atoi.
121 server
s(io_service
, atoi(argv
[1]));
125 catch (std::exception
& e
)
127 std::cerr
<< "Exception: " << e
.what() << "\n";