gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:54:41 31 4
gpt4 key购买 nike

如何使用 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 库还很陌生,所以我可能弄错了一些基础知识......

最佳答案

您必须调用 io_service::run(),这是将激活 io_service 的阻塞调用。

关于c++ - 如何使用 Beast websockets 进行异步读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44563284/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com