C++使用websocket例子
时间: 2023-07-08 07:34:35 浏览: 252
下面是一个使用 C++ 和 Boost.Beast 库实现的简单 WebSocket 示例:
```cpp
#include <iostream>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = net::ip::tcp;
int main() {
try {
net::io_context io_context;
// Connect to the server
tcp::resolver resolver(io_context);
auto const results = resolver.resolve("echo.websocket.org", "80");
websocket::stream<tcp::socket> ws(io_context);
net::connect(ws.next_layer(), results);
// Set a decorator to change the User-Agent of the handshake
ws.set_option(websocket::stream_base::decorator([](websocket::request_type& req) {
req.set(http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-coro");
}));
// Perform the websocket handshake
ws.handshake("echo.websocket.org", "/");
// Send a message to the server
ws.write(net::buffer(std::string("Hello, world!")));
// Receive a message from the server
beast::flat_buffer buffer;
ws.read(buffer);
std::cout << beast::make_printable(buffer.data()) << std::endl;
// Close the WebSocket connection
ws.close(websocket::close_code::normal);
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
```
在上面的代码中,我们使用 Boost.Beast 库来实现 WebSocket 客户端。我们首先创建一个 `io_context` 对象,然后使用 `tcp::resolver` 解析服务器的地址和端口号。接下来,我们创建一个 `websocket::stream` 对象,并使用 `net::connect` 连接到服务器。
我们设置一个装饰器来更改握手的 User-Agent。然后,我们调用 `ws.handshake` 方法来执行 WebSocket 握手。一旦握手成功,我们就可以使用 `ws.write` 方法将消息发送到服务器,并使用 `ws.read` 方法从服务器接收消息。最后,我们使用 `ws.close` 方法关闭 WebSocket 连接。
注意:在使用 Boost.Beast 库时,需要将其添加到项目依赖中,并在编译选项中添加 `-lboost_system` 和 `-lboost_thread`。
阅读全文
相关推荐


















