0

基于来自 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() 调用上挂起。也许这是我在正则表达式中看不到的一些愚蠢错误,我可以使用第一个版本,但我真的很想知道为什么会这样。

感谢您的任何见解,玛琳

4

0 回答 0