echo_server.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include "asio.hpp"
  2. #include <string>
  3. #include <iostream>
  4. #include "protocol_examples_common.h"
  5. #include "esp_event.h"
  6. #include "nvs_flash.h"
  7. using asio::ip::tcp;
  8. class session
  9. : public std::enable_shared_from_this<session>
  10. {
  11. public:
  12. session(tcp::socket socket)
  13. : socket_(std::move(socket))
  14. {
  15. }
  16. void start()
  17. {
  18. do_read();
  19. }
  20. private:
  21. void do_read()
  22. {
  23. auto self(shared_from_this());
  24. socket_.async_read_some(asio::buffer(data_, max_length),
  25. [this, self](std::error_code ec, std::size_t length)
  26. {
  27. if (!ec)
  28. {
  29. data_[length] = 0;
  30. std::cout << data_ << std::endl;
  31. do_write(length);
  32. }
  33. });
  34. }
  35. void do_write(std::size_t length)
  36. {
  37. auto self(shared_from_this());
  38. asio::async_write(socket_, asio::buffer(data_, length),
  39. [this, self](std::error_code ec, std::size_t length)
  40. {
  41. if (!ec)
  42. {
  43. do_read();
  44. }
  45. });
  46. }
  47. tcp::socket socket_;
  48. enum { max_length = 1024 };
  49. char data_[max_length];
  50. };
  51. class server
  52. {
  53. public:
  54. server(asio::io_context& io_context, short port)
  55. : acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
  56. {
  57. do_accept();
  58. }
  59. private:
  60. void do_accept()
  61. {
  62. acceptor_.async_accept(
  63. [this](std::error_code ec, tcp::socket socket)
  64. {
  65. if (!ec)
  66. {
  67. std::make_shared<session>(std::move(socket))->start();
  68. }
  69. do_accept();
  70. });
  71. }
  72. tcp::acceptor acceptor_;
  73. };
  74. extern "C" void app_main(void)
  75. {
  76. ESP_ERROR_CHECK(nvs_flash_init());
  77. esp_netif_init();
  78. ESP_ERROR_CHECK(esp_event_loop_create_default());
  79. /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
  80. * Read "Establishing Wi-Fi or Ethernet Connection" section in
  81. * examples/protocols/README.md for more information about this function.
  82. */
  83. ESP_ERROR_CHECK(example_connect());
  84. /* This helper function configures blocking UART I/O */
  85. ESP_ERROR_CHECK(example_configure_stdin_stdout());
  86. asio::io_context io_context;
  87. server s(io_context, std::atoi(CONFIG_EXAMPLE_PORT));
  88. std::cout << "ASIO engine is up and running" << std::endl;
  89. io_context.run();
  90. }