blocking_tcp_echo_client.cc 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // blocking_tcp_echo_client.cpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2010 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. using boost::asio::ip::tcp;
  15. enum
  16. {
  17. max_length = 1024
  18. };
  19. int main(int argc, char* argv[])
  20. {
  21. try
  22. {
  23. if (argc != 3)
  24. {
  25. std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
  26. return 1;
  27. }
  28. boost::asio::io_service io_service;
  29. tcp::resolver resolver(io_service);
  30. tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
  31. tcp::resolver::iterator iterator = resolver.resolve(query);
  32. tcp::socket s(io_service);
  33. s.connect(*iterator);
  34. using namespace std;
  35. // For strlen.
  36. std::cout << "Enter message: ";
  37. char request[max_length];
  38. std::cin.getline(request, max_length);
  39. size_t request_length = strlen(request);
  40. boost::asio::write(s, boost::asio::buffer(request, request_length));
  41. char reply[max_length];
  42. size_t reply_length = boost::asio::read(s, boost::asio::buffer(reply,
  43. request_length));
  44. std::cout << "Reply is: ";
  45. std::cout.write(reply, reply_length);
  46. std::cout << "\n";
  47. }
  48. catch (std::exception& e)
  49. {
  50. std::cerr << "Exception: " << e.what() << "\n";
  51. }
  52. return 0;
  53. }