]> git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/asio/example/cpp03/tutorial/daytime6/server.cpp
update sources to v12.2.3
[ceph.git] / ceph / src / boost / libs / asio / example / cpp03 / tutorial / daytime6 / 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/array.hpp>
15 #include <boost/bind.hpp>
16 #include <boost/shared_ptr.hpp>
17 #include <boost/asio.hpp>
18
19 using boost::asio::ip::udp;
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 udp_server
29 {
30 public:
31 udp_server(boost::asio::io_context& io_context)
32 : socket_(io_context, udp::endpoint(udp::v4(), 13))
33 {
34 start_receive();
35 }
36
37 private:
38 void start_receive()
39 {
40 socket_.async_receive_from(
41 boost::asio::buffer(recv_buffer_), remote_endpoint_,
42 boost::bind(&udp_server::handle_receive, this,
43 boost::asio::placeholders::error,
44 boost::asio::placeholders::bytes_transferred));
45 }
46
47 void handle_receive(const boost::system::error_code& error,
48 std::size_t /*bytes_transferred*/)
49 {
50 if (!error)
51 {
52 boost::shared_ptr<std::string> message(
53 new std::string(make_daytime_string()));
54
55 socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
56 boost::bind(&udp_server::handle_send, this, message,
57 boost::asio::placeholders::error,
58 boost::asio::placeholders::bytes_transferred));
59
60 start_receive();
61 }
62 }
63
64 void handle_send(boost::shared_ptr<std::string> /*message*/,
65 const boost::system::error_code& /*error*/,
66 std::size_t /*bytes_transferred*/)
67 {
68 }
69
70 udp::socket socket_;
71 udp::endpoint remote_endpoint_;
72 boost::array<char, 1> recv_buffer_;
73 };
74
75 int main()
76 {
77 try
78 {
79 boost::asio::io_context io_context;
80 udp_server server(io_context);
81 io_context.run();
82 }
83 catch (std::exception& e)
84 {
85 std::cerr << e.what() << std::endl;
86 }
87
88 return 0;
89 }