• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // async_udp_echo_server.cpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~
4 //
5 // Copyright (c) 2003-2021 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 <cstdlib>
12 #include <iostream>
13 #include <boost/asio.hpp>
14 
15 using boost::asio::ip::udp;
16 
17 class server
18 {
19 public:
server(boost::asio::io_context & io_context,short port)20   server(boost::asio::io_context& io_context, short port)
21     : socket_(io_context, udp::endpoint(udp::v4(), port))
22   {
23     do_receive();
24   }
25 
do_receive()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 
do_send(std::size_t length)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 
53 private:
54   udp::socket socket_;
55   udp::endpoint sender_endpoint_;
56   enum { max_length = 1024 };
57   char data_[max_length];
58 };
59 
main(int argc,char * argv[])60 int 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 
70     boost::asio::io_context io_context;
71 
72     server s(io_context, std::atoi(argv[1]));
73 
74     io_context.run();
75   }
76   catch (std::exception& e)
77   {
78     std::cerr << "Exception: " << e.what() << "\n";
79   }
80 
81   return 0;
82 }
83