[关闭]
@john-lee 2021-01-03T09:31:08.000000Z 字数 1183 阅读 545

套接字 Iostream(Socket Iostreams)

Boost.Asio


Boost.Asio 包括在套接字上实现 iostreams 的类。这些隐藏了与端点解析、协议独立性等相关的复杂性。要创建连接,只需编写:

  1. ip::tcp::iostream stream("www.boost.org", "http");
  2. if (!stream)
  3. {
  4. // Can't connect.
  5. }

iostream类还可以与接受器一起使用,以创建简单的服务器。例如:

  1. io_context ioc;
  2. ip::tcp::endpoint endpoint(tcp::v4(), 80);
  3. ip::tcp::acceptor acceptor(ios, endpoint);
  4. for (;;)
  5. {
  6. ip::tcp::iostream stream;
  7. acceptor.accept(stream.socket());
  8. ...
  9. }

可以通过调用expires_at()expires_from_now()来设置超时,以确定截止日期。任何超过最后期限的套接字操作都会使iostream进入“坏”状态。

例如,这样一个简单的客户端程序:

  1. ip::tcp::iostream stream;
  2. stream.expires_from_now(boost::posix_time::seconds(60));
  3. stream.connect("www.boost.org", "http");
  4. stream << "GET /LICENSE_1_0.txt HTTP/1.0\r\n";
  5. stream << "Host: www.boost.org\r\n";
  6. stream << "Accept: */*\r\n";
  7. stream << "Connection: close\r\n\r\n";
  8. stream.flush();
  9. std::cout << stream.rdbuf();

如果所有套接字操作的组合时间超过 60 秒,则将失败。

如果确实发生错误,可以使用iostream的error()成员函数从最近的系统调用中检索错误代码:

  1. if (!stream)
  2. {
  3. std::cout << "Error: " << stream.error().message() << "\n";
  4. }
另请参阅

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)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注