C++:websocketpp使用

news/2024/9/25 2:09:17/

文章目录

  • 一、官网地址
  • 二、简介
  • 三、安装
  • 四、使用

一、官网地址

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库:

apt-get install libboost-all-dev

下载websocketpp

git clone https://github.com/zaphoyd/websocketpp

编译安装

cd websocketcpp
mkdir build && cd build
cmake ..
make
make install

四、使用

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

#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;
};

其他地方调用

#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();

附送一个服务端代码

#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() {// 设置logm_endpoint.set_error_channels(websocketpp::log::elevel::all);m_endpoint.set_access_channels(websocketpp::log::alevel::all ^ websocketpp::log::alevel::frame_payload);// 初始化Asiom_endpoint.init_asio();// 设置消息回调为echo_handlerm_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() {// 监听端口 6666m_endpoint.listen(6666);m_endpoint.start_accept();// 开始Asio事件循环m_endpoint.run();}
private:server m_endpoint;
};int main() {utility_server s;s.run();return 0;
}

http://www.ppmy.cn/news/1446624.html

相关文章

spring boot运行过程中动态加载Controller

1.被加载的jar代码 package com.dl;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;SpringBootApplication public class App {public static void main(String[] args) {SpringApplication.run(A…

Leetcode—1041. 困于环中的机器人【中等】

2024每日刷题&#xff08;121&#xff09; Leetcode—1041. 困于环中的机器人 实现代码 class Solution { public:bool isRobotBounded(string instructions) {int x 0;int y 0;int d 0;vector<vector<int>> direction{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};for…

Java基础知识总结(82)

ConcurrentHashMap JDK 1.7中的ConcurrentHashMap 原理&#xff1a; JDK 1.7的ConcurrentHashMap的锁机制基于粒度更小的分段锁&#xff0c;分段锁其实是一种锁的设计&#xff0c;并不是具体的一种锁&#xff0c;对于ConcurrentHashMap而言&#xff0c;分段锁技术将Key分成一…

常用网络知识点(网管网工需掌握)

前言 最近在学习网络方面的内容时&#xff0c;看到很多知识点重复出现&#xff0c;不管在任何地方都能利用&#xff0c;我也就加班整理出一份针对于网络管理员/网络工程师等从业网络方面的知识点汇总 有需要的可以点赞搜藏慢慢看&#xff01;后续还会更新常见配置命令 BGP BGP…

Copilot Workspace是GitHub对人工智能驱动的软件工程的诠释

软件开发的未来是人工智能驱动的集成开发环境吗&#xff1f;至少GitHub 是这样想的。 在今年初秋于旧金山举行的 GitHub Universe 年度大会之前&#xff0c;GitHub 发布了 Copilot Workspace&#xff0c;这是一种开发环境&#xff0c;利用 GitHub 所称的 “Copilot 驱动的代理…

鸿蒙准备1

鸿蒙心路 感慨索性&#xff0c; 看看鸿蒙吧。打开官网相关介绍 新建工程目录结构 感慨 最近面试Android应用开发&#xff0c;动不动就问framework的知识&#xff0c;什么touch事件的触发源是啥&#xff08;eventHub&#xff09;&#xff0c;gc流程是啥&#xff0c;图形框架是什…

记录PR学习查漏补缺

记录PR学习查漏补缺 常用快捷键文件编辑素材序列标记字幕窗口帮助 效果基本3D高斯模糊查找边缘色彩颜色平衡超级键马赛克中间值变形稳定器 常用 快捷键 注意&#xff1a;比较常用的用红色字体显示 文件 快捷键作用Ctrl Alt N新建项目Ctrl O打开项目Ctrl I导入Ctrl S保存…

笔记-用Python脚本启停JAR程序

用Python脚本启停JAR程序&#xff0c;需要用到python中的以下内置模块 subprocess 是 Python 的一个标准库模块&#xff0c;用于在新进程中执行子命令&#xff0c;获取子进程的输入/输出/错误以及返回码等os 是 Python 的一个标准库模块&#xff0c;它提供了与操作系统交互的功…