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);
}
相关推荐
许长安16 分钟前
c/c++ static关键字详解
c语言·c++·经验分享·笔记
Murphy_lx35 分钟前
C++ thread类
开发语言·c++
月夜的风吹雨36 分钟前
【C++ STL 深度剖析】:vector 底层模拟实现与核心陷阱解析
c++·vector·类和对象·visual studio
彩妙不是菜喵43 分钟前
C++ 中 nullptr 的使用与实践:从陷阱到最佳实践
开发语言·jvm·c++
逐步前行1 小时前
C数据结构--排序算法
c语言·数据结构·排序算法
_dindong2 小时前
笔试强训:Week-4
数据结构·c++·笔记·学习·算法·哈希算法·散列表
liu****3 小时前
12.线程(二)
linux·开发语言·c++·1024程序员节
小冯的编程学习之路3 小时前
【C++】:C++基于微服务的即时通讯系统(2)
开发语言·c++·微服务
许长安4 小时前
C/C++中的extern关键字详解
c语言·开发语言·c++·经验分享·笔记
奔跑吧邓邓子4 小时前
【C语言实战(71)】C语言进阶:树与图的奇妙数据之旅
c语言···开发实战