blocking_tcp_echo_server.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //
  2. // blocking_tcp_echo_server.cpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 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 <thread>
  13. #include <utility>
  14. #include <boost/asio.hpp>
  15. using boost::asio::ip::tcp;
  16. const int max_length = 1024;
  17. void session(tcp::socket sock)
  18. {
  19. try
  20. {
  21. for (;;)
  22. {
  23. char data[max_length];
  24. boost::system::error_code error;
  25. size_t length = sock.read_some(boost::asio::buffer(data), error);
  26. if (error == boost::asio::error::eof)
  27. break; // Connection closed cleanly by peer.
  28. else if (error)
  29. throw boost::system::system_error(error); // Some other error.
  30. boost::asio::write(sock, boost::asio::buffer(data, length));
  31. }
  32. }
  33. catch (std::exception& e)
  34. {
  35. std::cerr << "Exception in thread: " << e.what() << "\n";
  36. }
  37. }
  38. void server(boost::asio::io_context& io_context, unsigned short port)
  39. {
  40. tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
  41. for (;;)
  42. {
  43. std::thread(session, a.accept()).detach();
  44. }
  45. }
  46. int main(int argc, char* argv[])
  47. {
  48. try
  49. {
  50. if (argc != 2)
  51. {
  52. std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
  53. return 1;
  54. }
  55. boost::asio::io_context io_context;
  56. server(io_context, std::atoi(argv[1]));
  57. }
  58. catch (std::exception& e)
  59. {
  60. std::cerr << "Exception: " << e.what() << "\n";
  61. }
  62. return 0;
  63. }