|
发表于 2024-4-2 15:50:13
|
显示全部楼层
浙江省杭州市
使用了第三方库 WebSocket++,它支持 WebSocket 客户Duan和服务器的开发
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>
#include <iostream>
// 命名空间
using namespace std;
// 定义 WebSocket 客户Duan类型
typedef websocketpp::client<websocketpp::config::asio_tls_client> client;
// 定义连接句柄类型
typedef websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context> context_ptr;
// 定义消息处理器
void on_message(client* c, websocketpp::connection_hdl hdl, client::message_ptr msg) {
cout << "Received: " << msg->get_payload() << endl;
}
int main() {
// 创建 WebSocket 客户Duan
client c;
try {
// 设置日志级别
c.set_access_channels(websocketpp::log::alevel::all);
c.clear_access_channels(websocketpp::log::alevel::frame_payload);
// 设置消息处理器
c.set_message_handler(bind(&on_message, &c, ::_1, ::_2));
// 创建连接
websocketpp::lib::error_code ec;
client::connection_ptr con = c.get_connection("ws://echo.websocket.org", ec);
if (ec) {
cout << "Error: " << ec.message() << endl;
return -1;
}
// 连接到服务器
c.connect(con);
// 发送中文文本数据
c.send(con, "你好,WebSocket!", websocketpp::frame::opcode::text, ec);
if (ec) {
cout << "Error sending message: " << ec.message() << endl;
return -1;
}
// 运行事件循环
c.run();
} catch (websocketpp::exception const & e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
|
|