echo_server.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "asio.hpp"
  2. #include <string>
  3. #include <iostream>
  4. using asio::ip::tcp;
  5. class session
  6. : public std::enable_shared_from_this<session>
  7. {
  8. public:
  9. session(tcp::socket socket)
  10. : socket_(std::move(socket))
  11. {
  12. }
  13. void start()
  14. {
  15. do_read();
  16. }
  17. private:
  18. void do_read()
  19. {
  20. auto self(shared_from_this());
  21. socket_.async_read_some(asio::buffer(data_, max_length),
  22. [this, self](std::error_code ec, std::size_t length)
  23. {
  24. if (!ec)
  25. {
  26. std::cout << data_ << std::endl;
  27. do_write(length);
  28. }
  29. });
  30. }
  31. void do_write(std::size_t length)
  32. {
  33. auto self(shared_from_this());
  34. asio::async_write(socket_, asio::buffer(data_, length),
  35. [this, self](std::error_code ec, std::size_t length)
  36. {
  37. if (!ec)
  38. {
  39. do_read();
  40. }
  41. });
  42. }
  43. tcp::socket socket_;
  44. enum { max_length = 1024 };
  45. char data_[max_length];
  46. };
  47. class server
  48. {
  49. public:
  50. server(asio::io_context& io_context, short port)
  51. : acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
  52. {
  53. do_accept();
  54. }
  55. private:
  56. void do_accept()
  57. {
  58. acceptor_.async_accept(
  59. [this](std::error_code ec, tcp::socket socket)
  60. {
  61. if (!ec)
  62. {
  63. std::make_shared<session>(std::move(socket))->start();
  64. }
  65. do_accept();
  66. });
  67. }
  68. tcp::acceptor acceptor_;
  69. };
  70. void asio_main()
  71. {
  72. asio::io_context io_context;
  73. server s(io_context, std::atoi(CONFIG_EXAMPLE_PORT));
  74. std::cout << "ASIO engine is up and running" << std::endl;
  75. io_context.run();
  76. }