]> git.proxmox.com Git - ceph.git/blame - ceph/src/boost/libs/asio/example/cpp11/echo/async_udp_echo_server.cpp
import new upstream nautilus stable release 14.2.8
[ceph.git] / ceph / src / boost / libs / asio / example / cpp11 / echo / async_udp_echo_server.cpp
CommitLineData
7c673cae
FG
1//
2// async_udp_echo_server.cpp
3// ~~~~~~~~~~~~~~~~~~~~~~~~~
4//
92f5a8d4 5// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7c673cae
FG
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 <cstdlib>
12#include <iostream>
13#include <boost/asio.hpp>
14
15using boost::asio::ip::udp;
16
17class server
18{
19public:
b32b8144
FG
20 server(boost::asio::io_context& io_context, short port)
21 : socket_(io_context, udp::endpoint(udp::v4(), port))
7c673cae
FG
22 {
23 do_receive();
24 }
25
26 void do_receive()
27 {
28 socket_.async_receive_from(
29 boost::asio::buffer(data_, max_length), sender_endpoint_,
30 [this](boost::system::error_code ec, std::size_t bytes_recvd)
31 {
32 if (!ec && bytes_recvd > 0)
33 {
34 do_send(bytes_recvd);
35 }
36 else
37 {
38 do_receive();
39 }
40 });
41 }
42
43 void do_send(std::size_t length)
44 {
45 socket_.async_send_to(
46 boost::asio::buffer(data_, length), sender_endpoint_,
47 [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/)
48 {
49 do_receive();
50 });
51 }
52
53private:
54 udp::socket socket_;
55 udp::endpoint sender_endpoint_;
56 enum { max_length = 1024 };
57 char data_[max_length];
58};
59
60int main(int argc, char* argv[])
61{
62 try
63 {
64 if (argc != 2)
65 {
66 std::cerr << "Usage: async_udp_echo_server <port>\n";
67 return 1;
68 }
69
b32b8144 70 boost::asio::io_context io_context;
7c673cae 71
b32b8144 72 server s(io_context, std::atoi(argv[1]));
7c673cae 73
b32b8144 74 io_context.run();
7c673cae
FG
75 }
76 catch (std::exception& e)
77 {
78 std::cerr << "Exception: " << e.what() << "\n";
79 }
80
81 return 0;
82}