stream_client.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // stream_client.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 <cstring>
  12. #include <iostream>
  13. #include <boost/asio.hpp>
  14. #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
  15. using boost::asio::local::stream_protocol;
  16. constexpr std::size_t max_length = 1024;
  17. int main(int argc, char* argv[])
  18. {
  19. try
  20. {
  21. if (argc != 2)
  22. {
  23. std::cerr << "Usage: stream_client <file>\n";
  24. return 1;
  25. }
  26. boost::asio::io_context io_context;
  27. stream_protocol::socket s(io_context);
  28. s.connect(stream_protocol::endpoint(argv[1]));
  29. std::cout << "Enter message: ";
  30. char request[max_length];
  31. std::cin.getline(request, max_length);
  32. size_t request_length = std::strlen(request);
  33. boost::asio::write(s, boost::asio::buffer(request, request_length));
  34. char reply[max_length];
  35. size_t reply_length = boost::asio::read(s,
  36. boost::asio::buffer(reply, request_length));
  37. std::cout << "Reply is: ";
  38. std::cout.write(reply, reply_length);
  39. std::cout << "\n";
  40. }
  41. catch (std::exception& e)
  42. {
  43. std::cerr << "Exception: " << e.what() << "\n";
  44. }
  45. return 0;
  46. }
  47. #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
  48. # error Local sockets not available on this platform.
  49. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)