实现真正boost的最简单的方法:: asio :: async_read_until

问题描述:

实现boost :: asio :: async_read_until版本的最简单方法是什么?只有在找到分隔符后才能读取?我可以实现一个特殊的匹配条件,知道如何使用适当的字节数量吗?如果不是,那么我该如何编写一个检查每个字节的异步读取器?实现真正boost的最简单的方法:: asio :: async_read_until

我需要停止提供的streambuf消耗超出分隔符的字节。

documentation你可以找到一个简单的匹配功能:

std::pair<iterator, bool> 
match_whitespace(iterator begin, iterator end) 
{ 
    iterator i = begin; 
    while (i != end) 
    if (std::isspace(*i++)) 
     return std::make_pair(i, true); 
    return std::make_pair(i, false); 
} 

在这种情况下,任何空白匹配(变化的std ::根据你想要什么isspace为)。此外该文档中,你可以看到一个更复杂的事件,它消耗的流,直到它找到一个特定的字符:

class match_char 
{ 
public: 
    explicit match_char(char c) : c_(c) {} 

    template <typename Iterator> 
    std::pair<Iterator, bool> operator()(
     Iterator begin, Iterator end) const 
    { 
    Iterator i = begin; 
    while (i != end) 
     if (c_ == *i++) 
     return std::make_pair(i, true); 
    return std::make_pair(i, false); 
    } 

private: 
    char c_; 
}; 

和代码使用该类:

// Function used for error handling 
void handler(const boost::system::error_code& e, std::size_t size) 
{ 
// Do something 
} 

// Example of call, it reads from inputStream to outputStreamBuff 
// until the specified delimiter (";") is found 
boost::asio::async_read_until(inputStream, outputStreamBuff, 
    match_char(';'), handler); 

我需要停止提供的streambuf消耗超出 定界符的字节。

完成此操作的唯一方法是(低效地)从流中一次读取一个字节。我不建议这种方法,documentation容易介绍了如何处理这种情况

成功async_read_until操作后,流缓冲可以 含有超出分隔符附加数据。应用程序 通常将该数据保留在streambuf中以供随后的async_read_until操作检查。

这正是异步http客户端example所做的。

我想指出this document中的REMARK实际上是不正确的,不管我测试多少次。

备注成功async_read_until操作之后,流缓冲 可以含有超出其相匹配的功能 对象的附加数据。应用程序通常会将该数据留在streambuf 中以供后续的async_read_until操作检查。

MatchCondition仿函数应该消耗streambuf中的所有内容,不要为未来的async_read_until()调用留下未消耗的字节,否则应用程序可能会永远等待。

p.s.测试设置是x86-64 centos4.3 kernel-2.6.32 gcc4.8

+0

更多用于测试设置:boost_1-59-0 – 2017-11-09 03:09:33