繁体   English   中英

提升ASIO streambuf

[英]Boost ASIO streambuf

我对boost asio :: streambuf类中的输入序列和输出序列感到困惑。

根据文档中的代码示例(用于发送数据),似乎表示输入序列的缓冲区用于写入socket,而表示输出序列的缓冲区用于读取。

示例 -

boost::asio::streambuf b;
std::ostream os(&b);
os << "Hello, World!\n";
// try sending some data in input sequence
size_t n = sock.send(b.data());
b.consume(n); // sent data is removed from input sequence

现在,有没有命名问题?

boost::asio::streambuf的命名法类似于C ++标准中定义的命名法,用于标准模板库中的各种类,其中数据被写入输出流并且数据从输入流中读取。 例如,可以使用std::cout.put()写入输出流,使用std::cin.get()从输入流中读取。

手动控制streambuf输入和输出序列时,数据的一般生命周期如下:

  • 缓冲区为输出序列分配了prepare()
  • 将数据写入输出序列的缓冲区后,数据将被commit() 此提交的数据将从输出序列中删除,并附加到可从中读取的输入序列。
  • 从通过data()获得的输入序列的缓冲区中读取data()
  • 读取数据后,可以通过consume()将其从输入序列中删除。

当使用上操作Boost.Asio的操作streambuf使用一个或流对象streambuf ,如std::ostream ,底层的输入和输出序列将进行适当的管理。 如果为操作提供了缓冲区,例如将prepare()传递给read操作或者将data()传递给write操作,则必须显式处理commit()consume()

以下是示例代码的带注释版本,它直接从streambuf写入套接字:

// The input and output sequence are empty.
boost::asio::streambuf b;
std::ostream os(&b);

// prepare() and write to the output sequence, then commit the written
// data to the input sequence.  The output sequence is empty and
// input sequence contains "Hello, World!\n".
os << "Hello, World!\n";

// Read from the input sequence, writing to the socket.  The input and
// output sequences remain unchanged.
size_t n = sock.send(b.data());

// Remove 'n' bytes from the input sequence. If the send operation sent
// the entire buffer, then the input sequence would be empty.
b.consume(n);

以下是从套接字直接读入streambuf的注释示例。 注释假设在套接字上已收到“hello”字样但尚未读取:

boost::asio::streambuf b;

// prepare() 512 bytes for the output sequence.  The input sequence
// is empty.
auto bufs = b.prepare(512);

// Read from the socket, writing into the output sequence.  The
// input sequence is empty and the output sequence contains "hello".
size_t n = sock.receive(bufs);

// Remove 'n' (5) bytes from output sequence appending them to the
// input sequence.  The input sequence contains "hello" and the
// output sequence has 507 bytes.
b.commit(n);

// The input and output sequence remain unchanged.
std::istream is(&b);
std::string s;

// Read from the input sequence and consume the read data.  The string
// 's' contains "hello".  The input sequence is empty, the output
// sequence remains unchanged.
is >> s;

请注意,在上面的示例中,处理的蒸汽对象已经提交并消耗了streambuf的输出和输入序列。 但是,当使用缓冲区本身(即data()prepare() )时,代码需要显式处理提交和使用。

“一切都是相对的”

艾尔伯特爱因斯坦

文件说:

写入basic_streambuf对象的输出序列的字符将附加到同一对象的输入序列中。

streambuf的角度来看,它将从其输出序列中读取并写入其输入序列,这可能看起来有点倒置,但您可以将streambuf视为事物有意义的管道

现在,从用户(使用streambuf ,包括套接字的任何东西)的观点来看,您将写入streambuf的输出序列并从其输入序列中读取,这似乎更自然。

所以是的,左右相同的方式取决于你所面对的东西,输入和输出是反转的,这取决于你看哪一面。

“不要相信你在互联网上读到的每一句话,因为我完全没有这么说”

艾尔伯特爱因斯坦

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM