C++:websocketpp使用

文章目录

一、官网地址

https://github.com/zaphoyd/websocketpp

参考

https://blog.csdn.net/qq_40344790/article/details/131207379

https://www.cnblogs.com/luckydml/p/11867319.html

二、简介

WebSocket++(简称WebSocketpp)是一个C++编写的WebSocket协议实现库,它提供了一个易于使用的接口,用于在C++应用程序中实现WebSocket客户端和服务器功能。WebSocket++支持WebSocket协议的最新标准,具有高度灵活性和可扩展性,适用于各种C++项目,包括网络服务器、实时通信应用程序等。

个人感受:WebSocketpp是一个成熟稳定的项目,相比于其他c++的websocket项目,更具有健全性。

三、安装

websocketpp库依赖boost_system,因此首先安装boost库:

shell 复制代码
apt-get install libboost-all-dev

下载websocketpp

shell 复制代码
git clone https://github.com/zaphoyd/websocketpp

编译安装

shell 复制代码
cd websocketcpp
mkdir build && cd build
cmake ..
make
make install

四、使用

由于我这里用于和ws服务端对接,所以我这里只用client;做了一个简单的封装。

c++ 复制代码
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <iostream>

typedef websocketpp::client<websocketpp::config::asio_client> client;

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;

typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
class connection
{
public:
    void on_open(websocketpp::connection_hdl hdl)
    {
        c.send(hdl, msg, websocketpp::frame::opcode::text);
        c.get_alog().write(websocketpp::log::alevel::app, "Tx: " + msg);
    }

    int init(std::string target_url,
        std::string first_message,
        std::function<void(websocketpp::connection_hdl, message_ptr)> message_handler)
    {
        uri = target_url;
        msg = first_message;
        c.set_access_channels(websocketpp::log::alevel::all);
        c.clear_access_channels(websocketpp::log::alevel::frame_payload);
        c.clear_access_channels(websocketpp::log::alevel::frame_header);
        c.init_asio();

        // 设置自定义回调的处理函数
        c.set_message_handler(message_handler);

     


        c.set_open_handler(websocketpp::lib::bind(&connection::on_open, this, _1));

        c.start_perpetual();
        thread_ = websocketpp::lib::make_shared<websocketpp::lib::thread>(&client::run, &c);
        return 0;
    }
    int connect()
    {
        websocketpp::lib::error_code ec;
        client::connection_ptr con = c.get_connection(uri, ec);
        if (ec)
        {
            std::cout << "could not create connection because: " << ec.message() << std::endl;

            return 0;
        }

        hdl_ = con->get_handle();
        c.connect(con);
        return 1;
    }


    // 发送消息方法
    void send_message(const std::string& message) {
    try {
        c.send(hdl_, message, websocketpp::frame::opcode::text);
        c.get_alog().write(websocketpp::log::alevel::app, "Tx: " + message);
    }
    catch (const websocketpp::exception& e) {
        // 捕获并处理异常
        std::cerr << "WebSocket Exception: " << e.what() << std::endl;
    }
    }
    // 发送二进制数据方法
    void send_binary_data(const std::vector<unsigned char>& data) {
        try {
            c.send(hdl_, data.data(), data.size(), websocketpp::frame::opcode::binary);
            c.get_alog().write(websocketpp::log::alevel::app, "Tx Binary Data");
        }
        catch (const websocketpp::exception& e) {
            // 捕获并处理异常
            std::cerr << "WebSocket Exception: " << e.what() << std::endl;
        }
    }
    void close()
    {
        try {
            c.close(hdl_, websocketpp::close::status::normal, "");
        }
        catch (const websocketpp::exception& e) {
            // 捕获并处理异常
            std::cerr << "WebSocket Exception: " << e.what() << std::endl;
        }
    }

    void terminate()
    {
        try {
            c.stop_perpetual();
            thread_->join();
        }
        catch (const websocketpp::exception& e) {
            // 捕获并处理异常
            std::cerr << "WebSocket Exception: " << e.what() << std::endl;
        }
    }
private:
    client c;
    websocketpp::lib::shared_ptr<websocketpp::lib::thread> thread_;
    websocketpp::connection_hdl hdl_;
    std::string uri;
    std::string  msg;
};

其他地方调用

c++ 复制代码
#include "websocketpp.cpp"

//1.设置回调函数
void reback_message(websocketpp::connection_hdl hdl, message_ptr msg)
{
    std::string message = msg->get_payload();
  
    websocketpp::lib::error_code ec;
    if (ec)
    {
     std::cerr << "WebSocket Exception: " << ec.message().c_str() << std::endl;
    }
    else{
     std::cout<< "WebSocket 收到服务器信息: " << message.c_str() << std::endl;

}
}

//1.初始化实例
connection* conn= new connection();


std::string url= "ws://127.0.0.1:6666";
std::string first_message = "websocket第一天初始化信息,可以不发,根据需求看代码";

  //2.初始化
  conn->init(url, first_message, reback_message);
  //3.连接到服务器 0连接失败1连接成功
  int res = conn->connect();
  //4.发送数据
  std::string date= "阿西吧,这是正常的文字";
  conn->send_message(date);
   // 准备要发送的数据
  std::vector<unsigned char> binary_data = {0x01, 0x02, 0x03, 0x04, 0x05};

  // 调用发送二进制数据的函数
  conn->send_binary_data(binary_data);
  //5.关闭
  conn->close();
 //6. 终止连接
  conn->terminate();

附送一个服务端代码

cpp 复制代码
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

#include <functional>

typedef websocketpp::server<websocketpp::config::asio> server;

class utility_server {
public:
    utility_server() {
         // 设置log
        m_endpoint.set_error_channels(websocketpp::log::elevel::all);
        m_endpoint.set_access_channels(websocketpp::log::alevel::all ^ websocketpp::log::alevel::frame_payload);

        // 初始化Asio
        m_endpoint.init_asio();

        // 设置消息回调为echo_handler
        m_endpoint.set_message_handler(std::bind(
            &utility_server::echo_handler, this,
            std::placeholders::_1, std::placeholders::_2
        ));
    }

    void echo_handler(websocketpp::connection_hdl hdl, server::message_ptr msg) {
        // 发送消息
        m_endpoint.send(hdl, msg->get_payload(), msg->get_opcode());
    }

    void run() {
        // 监听端口 6666
        m_endpoint.listen(6666);

       
        m_endpoint.start_accept();

        // 开始Asio事件循环
        m_endpoint.run();
    }
private:
    server m_endpoint;
};

int main() {
    utility_server s;
    s.run();
    return 0;
}
相关推荐
李日灐16 小时前
C++进阶必备:红黑树从 0 到 1: 手撕底层,带你搞懂平衡二叉树的平衡逻辑与黑高检验
开发语言·数据结构·c++·后端·面试·红黑树·自平衡二叉搜索树
汉克老师16 小时前
GESP2025年6月认证C++二级( 第一部分选择题(1-8))
c++·循环结构·表达式·分支结构·gesp二级·gesp2级
rainbow688916 小时前
C++高性能框架Drogon:后端开发新标杆
c++
Q741_14716 小时前
C++ 优先级队列 大小堆 模拟 力扣 703. 数据流中的第 K 大元素 每日一题
c++·算法·leetcode·优先级队列·
Yu_Lijing16 小时前
网络复习篇——网络基础(一)
网络·c++·笔记
Bella的成长园地16 小时前
为什么c++中的条件变量的 wait() 函数需要配合while 循环或谓词?
c++·面试
charlee4416 小时前
为什么现代 C++ 库都用 PIMPL?一场关于封装、依赖与安全的演进
c++·智能指针·raii·pimpl·编译防火墙·封装设计
MSTcheng.16 小时前
CANN ops-math算子的跨平台适配与硬件抽象层设计
c++·mfc
code monkey.16 小时前
【Linux之旅】Linux 进程间通信(IPC)全解析:从管道到共享内存,吃透进程协作核心
linux·c++·ipc
薛定谔的猫喵喵16 小时前
基于C++ Qt的唐代诗歌查询系统设计与实现
c++·qt·sqlite