带有正则表达式和超时的boost :: asio :: async_read_until - 奇怪的行为

时间:2013-06-06 10:59:03

标签: c++ regex timeout boost-asio

基于Boost示例中的代码(http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/timeouts/blocking_tcp_client.cpp) 我创建了一个函数read_expect(),如下所示:

std::string TcpClient::read_expect(const boost::regex & expected,
                                   boost::posix_time::time_duration timeout)
{
    // Set a deadline for the asynchronous operation. Since this function uses
    // a composed operation (async_read_until), the deadline applies to the
    // entire operation, rather than individual reads from the socket.
    deadline_.expires_from_now(timeout);

    // Set up the variable that receives the result of the asynchronous
    // operation. The error code is set to would_block to signal that the
    // operation is incomplete. Asio guarantees that its asynchronous
    // operations will never fail with would_block, so any other value in
    // ec indicates completion.
    boost::system::error_code ec = boost::asio::error::would_block;

    // Start the asynchronous operation itself. The boost::lambda function
    // object is used as a callback and will update the ec variable when the
    // operation completes. The blocking_udp_client.cpp example shows how you
    // can use boost::bind rather than boost::lambda.
    boost::asio::async_read_until(socket_, input_buffer_, expected, var(ec) = _1);

    // Block until the asynchronous operation has completed.
    do
    {
        io_service_.run_one();
    }
    while (ec == boost::asio::error::would_block);

    if (ec)
    {
        throw boost::system::system_error(ec);
    }

    // take the whole response
    std::string result;
    std::string line;
    std::istream is(&input_buffer_);
    while (is)
    {
        std::getline(is, line);
        result += line;
    }

    return result;
}

当我使用正则表达式

时,这可以正常工作
boost::regex(".*#ss#([^#]+)#.*")

,但是当我将正则表达式更改为

时,我会遇到奇怪的行为
boost::regex(".*#ss#(<Stats>[^#]+</Stats>)#.*")

,导致没有超时,导致线程挂起async_read_until()调用。 也许这是我在正则表达式中看不到的一些愚蠢的错误,我可以使用第一个版本,但我真的想知道为什么会发生这种情况。

感谢您的任何见解, 玛伦

0 个答案:

没有答案