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

时间:2012-03-27 14:53:40

标签: boost boost-asio

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

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

3 个答案:

答案 0 :(得分:1)

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);

答案 1 :(得分:0)

  

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

实现此目的的唯一方法是(无效地)从流中一次读取单个字节。我不建议这种方法,documentation很容易描述如何处理这种情况

  

成功执行async_read_until操作后,streambuf可以   包含分隔符之外的其他数据。申请将   通常将该数据留在streambuf中以供后续使用   要检查的async_read_until操作。

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

答案 2 :(得分:0)

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

  

备注成功执行async_read_until操作后,将获得streambuf   可能包含超出与函数匹配的数据的其他数据   宾语。应用程序通常会将该数据留在streambuf中   用于后续的async_read_until操作以进行检查。

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

P.S。测试设置为x86-64 centos4.3 kernel-2.6.32 gcc4.8