Ted*_*ton 9 c++ boost iostream boost-asio
我正在努力理解boost::asio::streambuf::consume()和boost::asio::streambuf::commit()打电话.在文档中,我们有例子,
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
Run Code Online (Sandbox Code Playgroud)
和
boost::asio::streambuf b;
// reserve 512 bytes in output sequence
boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);
size_t n = sock.receive(bufs);
// received data is "committed" from output sequence to input sequence
b.commit(n);
std::istream is(&b);
std::string s;
is >> s;
Run Code Online (Sandbox Code Playgroud)
我理解这两个调用就像我理解文档中有关它们的内容一样 - 调用consume()从内部的输入序列中删除字符boost::asio::streambuf,并调用commit()将字符从boost::asio::streambuf输出序列移动到其输入序列.很公平.
什么时候我居然把这些?看看boost::asio::read_until()来源,我们有
template <typename SyncReadStream, typename Allocator>
std::size_t read_until(SyncReadStream& s,
boost::asio::basic_streambuf<Allocator>& b, char delim,
boost::system::error_code& ec)
{
std::size_t search_position = 0;
for (;;)
{
// Determine the range of the data to be searched.
typedef typename boost::asio::basic_streambuf<
Allocator>::const_buffers_type const_buffers_type;
typedef boost::asio::buffers_iterator<const_buffers_type> iterator;
const_buffers_type buffers = b.data();
iterator begin = iterator::begin(buffers);
iterator start_pos = begin + search_position;
iterator end = iterator::end(buffers);
// Look for a match.
iterator iter = std::find(start_pos, end, delim);
if (iter != end)
{
// Found a match. We're done.
ec = boost::system::error_code();
return iter - begin + 1;
}
else
{
// No match. Next search can start with the new data.
search_position = end - begin;
}
// Check if buffer is full.
if (b.size() == b.max_size())
{
ec = error::not_found;
return 0;
}
// Need more data.
std::size_t bytes_to_read = read_size_helper(b, 65536);
b.commit(s.read_some(b.prepare(bytes_to_read), ec));
if (ec)
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以看到,正如文档所说,它boost::asio::read_until()是用SyncReadStream's' 来实现的read_some().
对我而言,这就是说
SyncReadStream::read_some() 不打电话 boost::asio::streambuf::commit()boost::asio::read_until() 打电话 boost::asio::streambuf::commit()boost::asio::read_until()文档中还是在SyncReadStream文档中.boost::asio::streambuf::commit()?用我的同步码当然,我似乎并不需要它,而不是当我拨打免费功能boost::asio::read()和boost::asio::read_until().我在我的处理程序中的异步代码中有它,主要是因为我使用的示例有它,但我不确定是否也可以调用它.当我尝试使用boost::asio::streambufwith stringstream和std::strings时,commit()似乎没有发挥作用 - 没有任何东西会在没有调用commit()的情况下停止或卡住streambuf.
任何人都可以为我排序吗?
read_until在他的实现中使用read_some。因此,read_some调用streambuf::commit但read_until不(直接)。
通常您不需要调用commitand consume,但如果您想对缓冲区数据执行某些操作 - 这可能是一种方法。例如,如果您使用二进制协议,则无法使用read_until.
| 归档时间: |
|
| 查看次数: |
3036 次 |
| 最近记录: |