1

我创建了一个异步野兽服务器,它从浏览器获取请求,打开第二个套接字,写入请求,获取响应并将其发送回浏览器。所有异步。因为“发送回浏览器”操作等待读取处理程序完成触发

void
on_write(
    boost::system::error_code ec,
    std::size_t bytes_transferred)
{
    boost::ignore_unused(bytes_transferred);

    if(ec)
        return fail2(ec, "write");
    std::cout << "===========on_write============" << std::endl;
    stopper("async_write" , 0);
    stopper("on_write" , 1);
    // Receive the HTTP response
    http::async_read(redirect_stream_, redirect_buffer_, redirect_res_,
        std::bind(
            &session2::on_read,
            shared_from_this(),
            std::placeholders::_1,
            std::placeholders::_2));
}

void
on_read(
    boost::system::error_code ec,
    std::size_t bytes_transferred)
{
    boost::ignore_unused(bytes_transferred);

    if(ec)
        return fail2(ec, "read");
    std::cout << "===========on_read============" << std::endl;
    stopper("on_write" , 0);
    stopper("on_read" , 1);
    // Write the message to standard out
    std::cout << redirect_res_.base() << std::endl;
    http::async_write(stream_, redirect_res_,
                      std::bind(
                          &session2::start_shutdown,
                          shared_from_this(),
                          std::placeholders::_1,
                          std::placeholders::_2));
    // Gracefully close the stream

}

似乎(根据我所做的检查)需要很长时间才能触发“写入浏览器”操作(on_read 函数)是否有更好的方法来减少对浏览器时间的响应?也许通过“read_some”方法?

4

1 回答 1

0

很大程度上取决于目标。如果您真的希望在不进行任何修改的情况下透明地转发请求/响应,那么 read_some 将是一种更好的方法(但您不需要 Beast 的任何东西,只需要 Asio)。

使用 Beast,您也可以读取部分请求,假设您可能想要修改有关正在中继的消息的一些内容,例如,您可以使用message_parser<...>代替message<>和使用http::read_header和循环来读取buffer_body.

文档中有一个示例实现了这样的事情:HTTP Relay example

你也可以搜索我的答案:https ://stackoverflow.com/search?q=user%3A85371+beast+read_header or for buffer_bodyand or request_parser/response_parser

除此之外,还有许多减少延迟的小方法(正确规划线程、执行器、分配器)。但是对于类似的事情,您可能应该发布您的代码(到 CodeReview?)。

于 2021-09-09T12:50:41.843 回答