如何使用Beast websockets进行异步读/写

时间:2017-06-15 09:03:57

标签: c++ boost websocket beast-websockets

如何使用Beast库中的websockets进行异步写入和读取?我试图调整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库一般都是新手,所以我可能会遇到一些错误的基础...

2 个答案:

答案 0 :(得分:3)

你必须调用io_service :: run(),这是阻塞调用,它将为io_service设置动画。

答案 1 :(得分:1)

现在可以学习或复制异步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