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