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);
}
相关推荐
qing_0406032 分钟前
C++——string的了解和使用
开发语言·c++·string
xiaobai12 339 分钟前
集群聊天服务器项目【C++】(六)MySql数据库
服务器·数据库·c++
奇点 ♡1 小时前
【线程】线程的控制
linux·运维·c语言·开发语言·c++·visual studio code
一道秘制的小菜1 小时前
C++第十一节课 new和delete
开发语言·数据结构·c++·学习·算法
心怀花木1 小时前
【C++】模拟实现list
c++·stl·list
kkk_皮蛋2 小时前
力扣773:滑动谜题
c++
float_com3 小时前
【STL】 set 与 multiset:基础、操作与应用
c++·stl
临沂堇3 小时前
CCF刷题计划——训练计划(反向拓扑排序)
数据结构·c++·算法·拓扑·ccf
铁匠匠匠3 小时前
【C总集篇】第八章 数组和指针
c语言·开发语言·数据结构·经验分享·笔记·学习·算法
猿饵块3 小时前
cmake--get_filename_component
java·前端·c++