Ubuntu websocket程序

转自:C/C++编程:WebSocketpp(Linux + Clion + boostAsio)_websocket++-CSDN博客

目前自己使用的:

复制代码
#include <functional>
#include <mutex>
#include <set>
#include <thread>

#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

typedef websocketpp::server<websocketpp::config::asio> server;
using websocketpp::connection_hdl;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;

class count_server{
public:
    count_server() : m_count(0){
        m_server.init_asio();

        m_server.set_open_handler(bind(&count_server::on_open,this,_1));
        m_server.set_close_handler(bind(&count_server::on_close,this,_1));
    }

    void on_open(connection_hdl hdl) {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_connections.insert(hdl);
    }

    void on_close(connection_hdl hdl) {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_connections.erase(hdl);
    }

    void count(){
        while (1){
            sleep(1);
            m_count++;

            std::stringstream  ss;
            ss << m_count;
            std::lock_guard<std::mutex> lock(m_mutex);
            for (auto it : m_connections) {
                m_server.send(it,ss.str(),websocketpp::frame::opcode::text);
            }
        }
    }

    void run(uint16_t port) {
        m_server.listen(port);
        m_server.start_accept();
        m_server.run();
    }
private:
    typedef std::set<connection_hdl,std::owner_less<connection_hdl>> con_list;

    int m_count;
    server m_server;
    con_list  m_connections;
    std::mutex  m_mutex;
};

int main(){
    count_server server;
    std::thread t(std::bind(&count_server::count,&server));
    server.run(9002);
}
相关推荐
David猪大卫31 分钟前
【C++修炼】智能指针使用及原理
开发语言·c++·经验分享·笔记·学习·考研·面试
李永奉39 分钟前
中科蓝讯SDK开发-BT893x 面条耳机连接vivo手机后连接APP端,最后手机端设置页面手动断开蓝牙连接,此时耳机端假断开
c语言·开发语言·嵌入式硬件·物联网·智能手机·电脑
零衣贰1 小时前
The 2026 ICPC Asia East Continent Online Contest (I) 题解
c++·icpc
fpcc2 小时前
c++编程实践—统一初始化
服务器·c++
Zenova EdgeOS3 小时前
C++ 工业边缘 libcurl HTTP 客户端实战
开发语言·c++·网络协议·边缘计算
爱吃苹果的日记本3 小时前
数据结构第一课
c语言·数据结构·数据库·学习·c#
Jackson_GJH4 小时前
Qt 右键自定义菜单的实现
开发语言·c++·qt
张小姐的猫4 小时前
【AI大模型接入SDK】 —— Gemini接入封装
android·数据结构·数据库·c++·人工智能·python
一木 之林4 小时前
七、一-AI 工程实践、插件化调试与软件交付
java·linux·c++
Murphy_lx6 小时前
1124. 表现良好的最长时间段
c++·算法