iostream_client.cpp 1.4 KB

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