【问题标题】:C++ Boost asio connect and streamC++ Boost asio 连接和流式传输
【发布时间】:2021-09-17 15:01:28
【问题描述】:

我是 Websockets 的新手,我对 boost::beast::websocket::stream 类的需求感到困惑。我在下面附上了一个示例代码。据我所知,socket.connect 将与 I/O 对象对话并建立与服务器的连接。那么为什么我需要将它传递给 websocket::stream 类,并使用该类执行握手、写入和读取数据?套接字中不应该有任何方法可以做到这一点吗?有人可以帮忙详细说明吗?谢谢

#include <boost/beast.hpp>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>

#include <iomanip>
#include <iostream>
#include <thread>

using tcp = boost::asio::ip::tcp;


int main()
{
    std::string url = "ltnm.learncppthroughprojects.com";
    std::string port = "80";
    // Create a I/O context
    boost::asio::io_context ioc {};
    // Create an I/O object, that takes in the io context as an intermediary to talk with you
    tcp::socket socket (ioc);

    // Resolve address to ip
    boost::system::error_code ec {};
    tcp::resolver resolver {ioc};
    auto resolverIt {resolver.resolve(url, port, ec)};

    // Talk to the socket using I/O context
    socket.connect(*resolverIt);

    // Now that talking to the socket is succcessful,
    // we tie the socket object to a websocket stream
    boost::beast::websocket::stream<boost::beast::tcp_stream> ws(std::move(socket));

    // Now, perform a websocket handshake
    ws.handshake(url,"/echo",ec);

    // Now the socket is connected to the server, write data to it
    boost::asio::const_buffer data("toioest",7);
    ws.write(data);
    
    boost::beast::flat_buffer response;
    ws.read(response);

    std::cout<<boost::beast::make_printable(response.data());
    
}

【问题讨论】:

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


    【解决方案1】:

    websocket::stream 类,并使用该类执行握手、写入和读取数据?

    这是因为websocket::stream 在任何 AsyncStream 上实现了 websocket 协议。这使得您可以插入管道、UNIX 域套接字、TCP 流或 SSL 流,并且该协议仍然适用于所有这些。

    套接字中不应该有任何方法可以做到这一点吗?

    哦,当然,但是你打破了 WebSocket 协议的抽象层,你很可能会打破它。

    这有点像说“但我不能直接在十六进制编辑器中按单词 docx 文件编写”。当然可以,但你不会更快乐,而且可能经常失去工作。

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 2011-03-31
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多