udp_echo_server.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 "tcpip_adapter.h"
  16. #include "nvs_flash.h"
  17. using asio::ip::udp;
  18. class server
  19. {
  20. public:
  21. server(asio::io_context& io_context, short port)
  22. : socket_(io_context, udp::endpoint(udp::v4(), port))
  23. {
  24. do_receive();
  25. }
  26. void do_receive()
  27. {
  28. socket_.async_receive_from(
  29. asio::buffer(data_, max_length), sender_endpoint_,
  30. [this](std::error_code ec, std::size_t bytes_recvd)
  31. {
  32. if (!ec && bytes_recvd > 0)
  33. {
  34. data_[bytes_recvd] = 0;
  35. std::cout << data_ << std::endl;
  36. do_send(bytes_recvd);
  37. }
  38. else
  39. {
  40. do_receive();
  41. }
  42. });
  43. }
  44. void do_send(std::size_t length)
  45. {
  46. socket_.async_send_to(
  47. asio::buffer(data_, length), sender_endpoint_,
  48. [this](std::error_code /*ec*/, std::size_t bytes /*bytes_sent*/)
  49. {
  50. do_receive();
  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. extern "C" void app_main()
  60. {
  61. ESP_ERROR_CHECK(nvs_flash_init());
  62. tcpip_adapter_init();
  63. ESP_ERROR_CHECK(esp_event_loop_create_default());
  64. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  65. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  66. * examples/protocols/README.md for more information about this function.
  67. */
  68. ESP_ERROR_CHECK(example_connect());
  69. /* This helper function configures blocking UART I/O */
  70. ESP_ERROR_CHECK(example_configure_stdin_stdout());
  71. asio::io_context io_context;
  72. server s(io_context, std::atoi(CONFIG_EXAMPLE_PORT));
  73. std::cout << "ASIO engine is up and running" << std::endl;
  74. io_context.run();
  75. }