首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Beast websockets进行异步读/写

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

Stack Overflow用户
提问于 2017-06-15 17:03:57
回答 0查看 4.3K关注 0票数 2

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

我期望得到以下输出:

代码语言:javascript
复制
*launch application*
Written data ...
Received data : Hello world!
*Ctrl-C*
Closing application ...

我得到了这个:

代码语言:javascript
复制
*launch application*
*Ctrl-C*
Closing application ...

代码:

代码语言:javascript
复制
#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库的新手,所以我可能把一些基础知识搞错了……

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44563284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档