udp_echo_server.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // async_udp_echo_server.cpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2018 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. #include <cstdlib>
  11. #include <iostream>
  12. #include "asio.hpp"
  13. #include "protocol_examples_common.h"
  14. #include "esp_event.h"
  15. #include "nvs_flash.h"
  16. using asio::ip::udp;
  17. class server
  18. {
  19. public:
  20. server(asio::io_context& io_context, short port)
  21. : socket_(io_context, udp::endpoint(udp::v4(), port))
  22. {
  23. do_receive();
  24. }
  25. void do_receive()
  26. {
  27. socket_.async_receive_from(
  28. asio::buffer(data_, max_length), sender_endpoint_,
  29. [this](std::error_code ec, std::size_t bytes_recvd)
  30. {
  31. if (!ec && bytes_recvd > 0)
  32. {
  33. data_[bytes_recvd] = 0;
  34. std::cout << data_ << std::endl;
  35. do_send(bytes_recvd);
  36. }
  37. else
  38. {
  39. do_receive();
  40. }
  41. });
  42. }
  43. void do_send(std::size_t length)
  44. {
  45. socket_.async_send_to(
  46. asio::buffer(data_, length), sender_endpoint_,
  47. [this](std::error_code /*ec*/, std::size_t bytes /*bytes_sent*/)
  48. {
  49. do_receive();
  50. });
  51. }
  52. private:
  53. udp::socket socket_;
  54. udp::endpoint sender_endpoint_;
  55. enum { max_length = 1024 };
  56. char data_[max_length];
  57. };
  58. extern "C" void app_main(void)
  59. {
  60. ESP_ERROR_CHECK(nvs_flash_init());
  61. esp_netif_init();
  62. ESP_ERROR_CHECK(esp_event_loop_create_default());
  63. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  64. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  65. * examples/protocols/README.md for more information about this function.
  66. */
  67. ESP_ERROR_CHECK(example_connect());
  68. /* This helper function configures blocking UART I/O */
  69. ESP_ERROR_CHECK(example_configure_stdin_stdout());
  70. asio::io_context io_context;
  71. server s(io_context, std::atoi(CONFIG_EXAMPLE_PORT));
  72. std::cout << "ASIO engine is up and running" << std::endl;
  73. io_context.run();
  74. }