首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >了解beast::tcp_stream中超时的用法吗?

了解beast::tcp_stream中超时的用法吗?
EN

Stack Overflow用户
提问于 2022-03-15 01:01:40
回答 1查看 364关注 0票数 1

参考资料:

async.cpp io/timeouts.html stream.html

代码语言:javascript
运行
复制
    void on_resolve(beast::error_code ec, tcp::resolver::results_type results)
    {
        if(ec) return fail(ec, "resolve");
        // Set the timeout for the operation
        beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(30));

        // Make the connection on the IP address we get from a lookup
        beast::get_lowest_layer(ws_).async_connect(
            results, beast::bind_front_handler(
                &session::on_connect, shared_from_this()));
    }

    void on_connect(beast::error_code ec, tcp::resolver::results_type::endpoint_type ep)
    {
        if(ec) return fail(ec, "connect");

        // Turn off the timeout on the tcp_stream, because
        // the websocket stream has its own timeout system.
        // beast::get_lowest_layer(ws_).expires_never(); // Note: do NOT call this line for this question!!!

...
        host_ += ':' + std::to_string(ep.port());
        // Perform the websocket handshake
        ws_.async_handshake(host_, "/",
            beast::bind_front_handler(&session::on_handshake, shared_from_this()));
    }

问题1>在以前的异步操作按时完成之后,beast::tcp_stream的超时会继续工作吗?

例如,在上面的示例中,超时将在30秒后过期。如果async_connect不能在30秒内完成,session::on_connect将接收一个error::timeout作为ec的值。假设async_connect需要10秒,我是否可以假设async_handshake需要在20秒(即30-10秒)内完成,否则error::timeout将被发送到session::on_handshake?我根据on_connect函数中的注释来推断这一想法。

关闭tcp_stream上的超时

)。换句话说,超时只有在完成指定的过期期或被expires_never禁用后才会被关闭。我的理解正确吗?

问题2>我还想知道在async_callingasync_callback函数中应该使用什么好的超时模式。

当我们调用async_calling操作时:

代码语言:javascript
运行
复制
void func_async_calling()
{
  // set some timeout here(i.e. XXXX seconds)
  Step 1> beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(XXXX));
  Step 2> ws_.async_operation(..., func_async_callback, )
  Step 3> beast::get_lowest_layer(ws_).expires_never();
}

当我们为异步操作定义async_callback句柄时:

代码语言:javascript
运行
复制
void func_async_callback()
{
  Step 1>Either call 
    // Disable the timeout for the next logical operation.
    beast::get_lowest_layer(ws_).expires_never(); 
  or
    // Enable a new timeout
    beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(YYYY));

  Step 2> call another asynchronous function
  Step 3> beast::get_lowest_layer(ws_).expires_never();
}

这有道理吗?

谢谢

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71475844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档