@john-lee
2021-01-03T09:31:08.000000Z
字数 1183
阅读 639
Boost.Asio
Boost.Asio 包括在套接字上实现 iostreams 的类。这些隐藏了与端点解析、协议独立性等相关的复杂性。要创建连接,只需编写:
ip::tcp::iostream stream("www.boost.org", "http");if (!stream){// Can't connect.}
iostream类还可以与接受器一起使用,以创建简单的服务器。例如:
io_context ioc;ip::tcp::endpoint endpoint(tcp::v4(), 80);ip::tcp::acceptor acceptor(ios, endpoint);for (;;){ip::tcp::iostream stream;acceptor.accept(stream.socket());...}
可以通过调用expires_at()或expires_from_now()来设置超时,以确定截止日期。任何超过最后期限的套接字操作都会使iostream进入“坏”状态。
例如,这样一个简单的客户端程序:
ip::tcp::iostream stream;stream.expires_from_now(boost::posix_time::seconds(60));stream.connect("www.boost.org", "http");stream << "GET /LICENSE_1_0.txt HTTP/1.0\r\n";stream << "Host: www.boost.org\r\n";stream << "Accept: */*\r\n";stream << "Connection: close\r\n\r\n";stream.flush();std::cout << stream.rdbuf();
如果所有套接字操作的组合时间超过 60 秒,则将失败。
如果确实发生错误,可以使用iostream的error()成员函数从最近的系统调用中检索错误代码:
if (!stream){std::cout << "Error: " << stream.error().message() << "\n";}
ip::tcp::iostream,basic_socket_iostream,iostreams 示例。
这些 iostream 模板只支持char,不支持wchar_t,并且不执行任何代码转换。
Copyright © 2003-2020 Christopher M. Kohlhoff
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)




