一、客户端代码
客户端代码-头文件
#ifndef Z__WEBSOCKET____m_client_H__
#define Z__WEBSOCKET____m_client_H__
#include <websocketpp/client.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
#include <iostream>
#include <functional>
#include <algorithm>
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
// WebSocket++ 客户端配置
using websocket_client = websocketpp::client<websocketpp::config::asio>;
// 定义消息处理器类
class ZWebsocketClient {
public:
ZWebsocketClient();
// 连接成功回调函数
void on_open(websocketpp::connection_hdl hdl);
// 消息接收回调函数
void on_message(websocketpp::connection_hdl hdl, websocket_client::message_ptr msg);
// 连接关闭回调函数
void on_close(websocketpp::connection_hdl hdl);
// 运行 WebSocket 客户端
void run(const std::string& ip, const int port);
private:
// WebSocket 客户端对象
websocket_client m_client;
};
#endif // ! Z__WEBSOCKET____m_client_H__
客户端代码-实现
#include "WebSocketClient.h"
ZWebsocketClient::ZWebsocketClient()
{
// 设置连接成功回调函数
m_client.set_open_handler(std::bind(&ZWebsocketClient::on_open, this, ::_1));
// 设置消息接收回调函数
m_client.set_message_handler(std::bind(&ZWebsocketClient::on_message, this, ::_1, ::_2));
// 设置连接关闭回调函数
m_client.set_close_handler(std::bind(&ZWebsocketClient::on_close, this, ::_1));
}
// 连接成功回调函数
void ZWebsocketClient::