Boost :: Beast:具有websocket管道的服务器

时间:2019-05-20 13:42:11

标签: c++ boost-asio boost-beast

我正在编写带有Boost Beast 1.70和mysql 8 C连接器的C ++ Websocket服务器。该服务器将同时连接多个客户端。特殊之处在于,每个客户端将连续向服务器执行100个websocket请求。对于我的服务器,每个请求都是“ cpu light”,但是服务器会为每个请求执行“时间密集” sql请求。

我已使用websocket_server_coro.cpp示例启动了服务器。服务器步骤为:

1)读入一个网络套接字

2)一个SQL请求

3)一个websocket写入

问题在于对于给定的用户,服务器在步骤2被“锁定”,并且在完成该步骤和步骤3之前无法读取。因此,依次解决了100个请求。对于我的用例来说,这太慢了。

我已经读到,增强兽无法进行非阻塞的读/写。但是,我现在要做的是在协程中执行async_read和async_write。

void ServerCoro::accept(websocket::stream<beast::tcp_stream> &ws) {
    beast::error_code ec;

    ws.set_option(websocket::stream_base::timeout::suggested(beast::role_type::server));

    ws.set_option(websocket::stream_base::decorator([](websocket::response_type &res) {
                res.set(http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-Server-coro");
            }));

    ws.async_accept(yield[ec]);
    if (ec) return fail(ec, "accept");

    while (!_bStop) {
        beast::flat_buffer buffer;
        ws.async_read(buffer, yield[ec]);

        if (ec == websocket::error::closed) {
            std::cout << "=> get closed" << std::endl;
            return;
        }

        if (ec) return fail(ec, "read");

        auto buffer_str = new std::string(boost::beast::buffers_to_string(buffer.cdata()));
        net::post([&, buffer_str] {

            // sql async request such as :
            // while (status == (mysql_real_query_nonblocking(this->con, sqlRequest.c_str(), sqlRequest.size()))) {
            //    ioc.poll_one(ec);
            // }
            // more sql ...

            ws.async_write(net::buffer(worker->getResponse()), yield[ec]); // this line is throwing void boost::coroutines::detail::pull_coroutine_impl<void>::pull(): Assertion `! is_running()' failed.
            if (ec) return fail(ec, "write");

        });
    }
}

问题在于,带有async_write的行抛出错误:

无效提升::协程::细节:: pull_coroutine_impl :: pull():断言`! is_running()'失败。

如果将此行替换为sync_write,则可以运行,但是服务器对于给定用户保持顺序。 我试图在单线程服务器上执行此代码。我也曾尝试对async_read和async_write使用同一链。仍然有断言错误。

使用websocket的增强野兽无法实现这样的服务器吗? 谢谢。

1 个答案:

答案 0 :(得分:1)

根据Vinnie Falco的建议,我以“ websocket chat”和“ async server”为例重写了代码。这是代码的最终工作结果:

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

    if(ec == websocket::error::closed) return;  // This indicates that the Session was closed
    if(ec) return fail(ec, "read");

    net::post([&, that = shared_from_this(), ss = std::make_shared<std::string const>(std::move(boost::beast::buffers_to_string(_buffer.cdata())))] {
        /* Sql things that call ioc.poll_one(ec) HERE, for me the sql response go inside worker.getResponse() used below */

        net::dispatch(_wsStrand, [&, that = shared_from_this(), sss = std::make_shared < std::string const>(worker.getResponse())] {
            async_write(sss);
        });
    });
    _buffer.consume(_buffer.size()); // we remove from the buffer what we just read
    do_read(); // go for another read
}

void Session::async_write(const std::shared_ptr<std::string const> &message) {
    _writeMessages.push_back(message);

    if (_writeMessages.size() > 1) {
        BOOST_LOG_TRIVIAL(warning) << "WRITE IS LOCKED";
    } else {
        _ws.text(_ws.got_text());
            _ws.async_write(net::buffer(*_writeMessages.front()), boost::asio::bind_executor(_wsStrand, beast::bind_front_handler(
                    &Session::on_write, this)));
    }
}

void Session::on_write(beast::error_code ec, std::size_t)
{
    // Handle the error, if any
    if(ec) return fail(ec, "write");

    // Remove the string from the queue
    _writeMessages.erase(_writeMessages.begin());

    // Send the next message if any
    if(!_writeMessages.empty())
        _ws.async_write(net::buffer(*_writeMessages.front()), boost::asio::bind_executor(_wsStrand, beast::bind_front_handler(
                        &Session::on_write, this)));
}

谢谢。

相关问题