【问题标题】:How to do async read/write with Beast websockets如何使用 Beast websockets 进行异步读/写
【发布时间】:2017-06-15 09:03:57
【问题描述】:

如何使用 Beast 库中的 websocket 进行异步读写?我已尝试调整 Beast 文档here 中提供的同步写入/读取示例,但以下代码的行为与预期不符。

我希望得到以下输出:

*launch application*
Written data ...
Received data : Hello world!
*Ctrl-C*
Closing application ...

我明白了:

*launch application*
*Ctrl-C*
Closing application ...

代码:

#include <beast/core/to_string.hpp>
#include <beast/websocket.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <string>

/// Block until SIGINT or SIGTERM is received.
void sig_wait(beast::websocket::stream<boost::asio::ip::tcp::socket&>& ws)
{
    boost::asio::io_service ios;
    boost::asio::signal_set signals(ios, SIGINT, SIGTERM);
    signals.async_wait(
        [&](boost::system::error_code const&, int)
        {
            ws.close(beast::websocket::close_code::normal);
            std::cout << "Closing application ..." << std::endl;
        });
    ios.run();
}

int main(int argc, char *argv[])
{
    // Normal boost::asio setup
    std::string const host = "echo.websocket.org";
    boost::asio::io_service ios;
    boost::asio::ip::tcp::resolver r{ios};
    boost::asio::ip::tcp::socket sock{ios};
    boost::asio::ip::tcp::resolver::iterator iter (r.resolve(boost::asio::ip::tcp::resolver::query{host, "80"}));
    boost::asio::connect(sock,iter);

    // WebSocket connect and send message
    beast::websocket::stream<boost::asio::ip::tcp::socket&> ws{sock};
    ws.handshake(host, "/");
    ws.async_write(boost::asio::buffer(std::string("Hello world!")),
                   [&](beast::error_code const&)
                     {
                         std::cout << "Written data ..." << '\n';
                     }
    );

    // Register handle for async_read
    beast::streambuf sb;
    beast::websocket::opcode op;
    ws.async_read(op,sb,
                  [&](beast::error_code const&)
                    {
                        std::cout << "Received data : " << to_string(sb.data()) << '\n';
                    }
    );

    sig_wait(ws);
}

旁注:总的来说,我对 Boost 库还很陌生,所以我可能弄错了一些基础知识...

【问题讨论】:

    标签: c++ boost websocket beast-websockets


    【解决方案1】:

    您必须调用 io_service::run(),这就是将动画 io_service 的阻塞调用。

    【讨论】:

    • 这不是答案。这是一个问题!
    • 我期待 websocket 流在幕后处理 io 服务。我的假设错了吗?
    • 是的,你必须调用 run()。这就是包含 io 循环的阻塞调用,它发挥了魔力..
    • @celavek 抱歉,我会改写。
    • 我已经接受了这个答案,因为在调用 sig_wait() 之前调用 ios.run() 确实会产生预期的结果。
    【解决方案2】:

    现在有异步WebSocket客户端例子可以学习或复制:http://www.boost.org/doc/libs/develop/libs/beast/doc/html/beast/examples.html

    这是一个异步客户端示例,它从 main 调用 io_service::run(): http://www.boost.org/doc/libs/develop/libs/beast/example/websocket/client/async/websocket_client_async.cpp

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2017-10-27
      • 1970-01-01
      • 2019-11-28
      • 2015-09-19
      相关资源
      最近更新 更多