echo_server.cpp 2.2 KB

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