iostreams.qbk 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. [/
  2. / Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  3. /
  4. / Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. /]
  7. [section:iostreams Socket Iostreams]
  8. Boost.Asio includes classes that implement iostreams on top of sockets. These hide
  9. away the complexities associated with endpoint resolution, protocol
  10. independence, etc. To create a connection one might simply write:
  11. ip::tcp::iostream stream("www.boost.org", "http");
  12. if (!stream)
  13. {
  14. // Can't connect.
  15. }
  16. The iostream class can also be used in conjunction with an acceptor to create
  17. simple servers. For example:
  18. io_context ioc;
  19. ip::tcp::endpoint endpoint(tcp::v4(), 80);
  20. ip::tcp::acceptor acceptor(ios, endpoint);
  21. for (;;)
  22. {
  23. ip::tcp::iostream stream;
  24. acceptor.accept(stream.socket());
  25. ...
  26. }
  27. Timeouts may be set by calling `expires_at()` or `expires_from_now()` to
  28. establish a deadline. Any socket operations that occur past the deadline will
  29. put the iostream into a "bad" state.
  30. For example, a simple client program like this:
  31. ip::tcp::iostream stream;
  32. stream.expires_from_now(boost::posix_time::seconds(60));
  33. stream.connect("www.boost.org", "http");
  34. stream << "GET /LICENSE_1_0.txt HTTP/1.0\r\n";
  35. stream << "Host: www.boost.org\r\n";
  36. stream << "Accept: */*\r\n";
  37. stream << "Connection: close\r\n\r\n";
  38. stream.flush();
  39. std::cout << stream.rdbuf();
  40. will fail if all the socket operations combined take longer than 60 seconds.
  41. If an error does occur, the iostream's `error()` member function may be used to
  42. retrieve the error code from the most recent system call:
  43. if (!stream)
  44. {
  45. std::cout << "Error: " << stream.error().message() << "\n";
  46. }
  47. [heading See Also]
  48. [link boost_asio.reference.ip__tcp.iostream ip::tcp::iostream],
  49. [link boost_asio.reference.basic_socket_iostream basic_socket_iostream],
  50. [link boost_asio.examples.cpp03_examples.iostreams iostreams examples].
  51. [heading Notes]
  52. These iostream templates only support `char`, not `wchar_t`, and do not perform
  53. any code conversion.
  54. [endsect]