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)
14 #include <boost/array.hpp>
15 #include <boost/bind.hpp>
16 #include <boost/shared_ptr.hpp>
17 #include <boost/enable_shared_from_this.hpp>
18 #include <boost/asio.hpp>
20 using boost::asio::ip::tcp
;
21 using boost::asio::ip::udp
;
23 std::string
make_daytime_string()
25 using namespace std
; // For time_t, time and ctime;
31 : public boost::enable_shared_from_this
<tcp_connection
>
34 typedef boost::shared_ptr
<tcp_connection
> pointer
;
36 static pointer
create(boost::asio::io_context
& io_context
)
38 return pointer(new tcp_connection(io_context
));
48 message_
= make_daytime_string();
50 boost::asio::async_write(socket_
, boost::asio::buffer(message_
),
51 boost::bind(&tcp_connection::handle_write
, shared_from_this()));
55 tcp_connection(boost::asio::io_context
& io_context
)
71 tcp_server(boost::asio::io_context
& io_context
)
72 : acceptor_(io_context
, tcp::endpoint(tcp::v4(), 13))
80 tcp_connection::pointer new_connection
=
81 tcp_connection::create(acceptor_
.get_executor().context());
83 acceptor_
.async_accept(new_connection
->socket(),
84 boost::bind(&tcp_server::handle_accept
, this, new_connection
,
85 boost::asio::placeholders::error
));
88 void handle_accept(tcp_connection::pointer new_connection
,
89 const boost::system::error_code
& error
)
93 new_connection
->start();
99 tcp::acceptor acceptor_
;
105 udp_server(boost::asio::io_context
& io_context
)
106 : socket_(io_context
, udp::endpoint(udp::v4(), 13))
114 socket_
.async_receive_from(
115 boost::asio::buffer(recv_buffer_
), remote_endpoint_
,
116 boost::bind(&udp_server::handle_receive
, this,
117 boost::asio::placeholders::error
));
120 void handle_receive(const boost::system::error_code
& error
)
124 boost::shared_ptr
<std::string
> message(
125 new std::string(make_daytime_string()));
127 socket_
.async_send_to(boost::asio::buffer(*message
), remote_endpoint_
,
128 boost::bind(&udp_server::handle_send
, this, message
));
134 void handle_send(boost::shared_ptr
<std::string
> /*message*/)
139 udp::endpoint remote_endpoint_
;
140 boost::array
<char, 1> recv_buffer_
;
147 boost::asio::io_context io_context
;
148 tcp_server
server1(io_context
);
149 udp_server
server2(io_context
);
152 catch (std::exception
& e
)
154 std::cerr
<< e
.what() << std::endl
;