stream_client.cpp 1.5 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 <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. enum { 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. using namespace std; // For strlen.
  30. std::cout << "Enter message: ";
  31. char request[max_length];
  32. std::cin.getline(request, max_length);
  33. size_t request_length = strlen(request);
  34. boost::asio::write(s, boost::asio::buffer(request, request_length));
  35. char reply[max_length];
  36. size_t reply_length = boost::asio::read(s,
  37. boost::asio::buffer(reply, request_length));
  38. std::cout << "Reply is: ";
  39. std::cout.write(reply, reply_length);
  40. std::cout << "\n";
  41. }
  42. catch (std::exception& e)
  43. {
  44. std::cerr << "Exception: " << e.what() << "\n";
  45. }
  46. return 0;
  47. }
  48. #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
  49. # error Local sockets not available on this platform.
  50. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)