【问题标题】:Boost beast::websocket callback functionsBoost beast::websocket 回调函数
【发布时间】:2018-10-06 10:33:03
【问题描述】:

我正在试验 Boost beast::websocket websocket_client_async.cpp 示例,以及 websocket_server_async.cpp

如给定的那样,client 示例只是建立一个连接,向服务器发送一个字符串(它只是回显),打印回复,关闭并存在。

我正在尝试修改客户端以使会话保持活动状态,以便我可以重复发送/接收字符串。因此,虽然示例代码的 on_handshake 函数会立即通过 ws_.async_write(...) 发送字符串,但我将其分离到自己的 write(...) 函数中。

这是我修改后的session 类:

using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;

void fail(boost::system::error_code ec, char const* what)
{
    std::cerr << what << ": " << ec.message() << "\n";
}

// Sends a WebSocket message and prints the response
class session : public std::enable_shared_from_this<session>
{
    tcp::resolver resolver_;
    websocket::stream<tcp::socket> ws_;
    std::atomic<bool> io_in_progress_;
    boost::beast::multi_buffer buffer_;
    std::string host_;

public:
    // Resolver and socket require an io_context
    explicit session(boost::asio::io_context& ioc) : resolver_(ioc), ws_(ioc) {
        io_in_progress_ = false;
    }

    bool io_in_progress() const {
        return io_in_progress_;
    }

    // +---------------------+
    // | The "open" sequence |
    // +---------------------+
    void open(char const* host, char const* port)
    {
        host_ = host;

        // Look up the domain name
        resolver_.async_resolve(host, port,
            std::bind( &session::on_resolve, shared_from_this(),
                std::placeholders::_1, std::placeholders::_2 )
        );
    }

    void on_resolve(boost::system::error_code ec, tcp::resolver::results_type results)
    {
        if (ec)
            return fail(ec, "resolve");

        boost::asio::async_connect(
            ws_.next_layer(), results.begin(), results.end(),
            std::bind( &session::on_connect, shared_from_this(),
                std::placeholders::_1 )
        );
    }

    void on_connect(boost::system::error_code ec)
    {
        if (ec)
            return fail(ec, "connect");

        ws_.async_handshake(host_, "/",
            std::bind( &session::on_handshake, shared_from_this(),
                std::placeholders::_1 )
        );
    }

    void on_handshake(boost::system::error_code ec)
    {
        if (ec)
            return fail(ec, "handshake");
        else {
            std::cout << "Successful handshake with server.\n";
        }
    }

    // +---------------------------+
    // | The "write/read" sequence |
    // +---------------------------+
    void write(const std::string &text)
    {
        io_in_progress_ = true;
        ws_.async_write(boost::asio::buffer(text),
            std::bind( &session::on_write, shared_from_this(),
                std::placeholders::_1, std::placeholders::_2 )
        );
    }

    void on_write(boost::system::error_code ec, std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);
        if (ec)
            return fail(ec, "write");

        ws_.async_read(buffer_,
            std::bind( &session::on_read, shared_from_this(),
                std::placeholders::_1, std::placeholders::_2 )
        );
    }

    void on_read(boost::system::error_code ec, std::size_t bytes_transferred)
    {
        io_in_progress_ = false; // end of write/read sequence
        boost::ignore_unused(bytes_transferred);
        if (ec)
            return fail(ec, "read");

        std::cout << boost::beast::buffers(buffer_.data()) << std::endl;
    }

    // +----------------------+
    // | The "close" sequence |
    // +----------------------+
    void close()
    {
        io_in_progress_ = true;
        ws_.async_close(websocket::close_code::normal,
            std::bind( &session::on_close, shared_from_this(),
                std::placeholders::_1)
        );
    }

    void on_close(boost::system::error_code ec)
    {
        io_in_progress_ = false; // end of close sequence
        if (ec)
            return fail(ec, "close");

        std::cout << "Socket closed successfully.\n";
    }
};

问题是,虽然连接工作正常并且我可以发送一个字符串,但 on_read 回调永远不会被击中(除非我做了下面描述的丑陋黑客攻击)。

我的main 看起来像这样:

void wait_for_io(std::shared_ptr<session> psession, boost::asio::io_context &ioc)
{
    // Continually try to run the ioc until the callbacks are finally
    // triggered (as indicated by the session::io_in_progress_ flag)
    while (psession->io_in_progress()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        ioc.run();
    }
}

int main(int argc, char** argv)
{
    // Check command line arguments.
    if (argc != 3) {
        std::cerr << "usage info goes here...\n";
        return EXIT_FAILURE;
    }
    const char *host = argv[1], *port = argv[2];

    boost::asio::io_context ioc;
    std::shared_ptr<session> p = std::make_shared<session>(ioc);
    p->open(host, port);
    ioc.run(); // This works. Connection is established and all callbacks are executed.

    p->write("Hello world"); // String is sent & received by server,
                             // even before calling ioc.run()
                             // However, session::on_read callback is never
                             // reached.

    ioc.run();               // This seems to be ignored and returns immediately, so
    wait_for_io(p, ioc);     // <-- so this hack is necessary

    p->close();              // session::on_close is never reached
    ioc.run();               // Again, this seems to be ignored and returns immediately, so
    wait_for_io(p, ioc);     // <-- this is necessary

    return EXIT_SUCCESS;
}

如果我这样做:

p->write("Hello world");
while(1) {
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
}

我可以确认该字符串已由服务器发送和接收1,并且session::on_read 回调到达。

p-&gt;close() 也会发生同样的事情。

但是,如果我添加我奇怪的 wait_for_io() 函数,一切正常。我很肯定这是一个可怕的黑客攻击,但我无法弄清楚发生了什么。

1 注意:我可以确认消息确实到达了服务器,因为我修改了服务器示例以将任何接收到的字符串打印到控制台。这是我做的唯一修改。回显到客户端的功能没有改变。

【问题讨论】:

  • 只是一个观察,这段代码有未定义的行为。您在write 中呼叫boost::asio::buffer(text)。但是text 可以在异步操作仍在运行时超出范围。调用者有责任确保传递给流算法的内存缓冲区的生命周期至少在调用相应的完成处理程序之前保持有效。
  • @VinnieFalco 哎呀...好点。这只是我在为 SO.SE 格式化代码时犯的一个愚蠢的转录错误。

标签: c++ boost websocket


【解决方案1】:

io_context::run 只会在没有更多待处理的工作时返回。如果您只是确保始终有对 websocket::stream::async_read 的挂起调用处于活动状态,那么 run 将永远不会返回,并且不需要黑客攻击。此外,您将收到服务器发送的所有消息。

【讨论】:

  • 谢谢维尼。我确实理解这一点,并从一开始就以这种方式对其进行了测试,但是当我想关闭套接字时,很难干净地结束挂起的调用。但是,老实说,我看不出我上面的代码如何不符合您在第一句话中写的内容。当我调用 p->write(...);就在 ioc.run(); 之前有待处理的工作。然后应该进行阅读。
  • 澄清一下,当我调用 p->write(...) 时,函数本身会创建工作 - 这就是为什么我不明白 ioc.run() 无法做任何事情的原因。
  • 如果你想关闭websocket连接,只需调用async_close。确保从用于进行其他调用的相同隐式或显式链中执行此操作。当async_close 操作完成时,对async_readasync_write 的挂起调用最终将分别以websocket::error::closedboost::asio::operation_aborted 完成。我不确定为什么io_context::run 会立即返回,但这只能是因为没有待处理的工作。
  • 是的,调用async_close 确实有效 - 我不确定我之前遇到的问题是什么;这很简单。也许我忘了加入线程或愚蠢的东西。但这有点离题了。我的问题实际上是关于为什么上面的代码不起作用。现在,我只是在测试我对库的理解,以确保我牢牢掌握编写我的操作代码。在继续之前,我想解开这个谜团。我开始认为这是库中的错误。
  • 如果最新版本的 Beast 存在缺陷,我会感到非常惊讶。通过测试,代码几乎有 100% 的覆盖率,而且测试非常详尽。示例客户端和服务器按书面方式工作。如果他们停止工作,那肯定是因为所做的任何更改。我会重新开始使用原始代码并验证它是否按预期工作,然后逐步应用您的更改以找出导致它出现故障的原因。
【解决方案2】:

第一次调用后对io_context::run() 的调用不起作用的原因(此处显示):

boost::asio::io_context ioc;
std::shared_ptr<session> p = std::make_shared<session>(ioc);
p->open(host, port);
ioc.run(); // This works. Connection is established and all callbacks are executed.

是因为函数 io_context::restart() 必须在任何后续调用 io_context::run 之前调用。

From the documentation:

io_context::restart

重新启动 io_context 以准备后续的 run() 调用。

此函数必须在 run()、run_one()、 poll() 或 poll_one() 函数,当这些函数的先前调用由于 io_context 停止或耗尽工作而返回时。调用restart()后,io_context对象的stopped()函数会返回false。

【讨论】:

  • gah...每次我都忘记打电话给restart
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 2018-11-26
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 2021-07-10
相关资源
最近更新 更多