blocking_tcp_echo_server.cpp 1.8 KB

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