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);
}
相关推荐
曦樂~5 小时前
Cpp面筋
c语言·c++
道尔柯南5 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
十二8 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
D e re k ZH10 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
zjxtxdy12 小时前
C++面向对象程序开发-类与对象
开发语言·c++
東隅已逝,桑榆非晚13 小时前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法
qq_4069810314 小时前
c++拷贝构造函数
开发语言·c++
HUANGZHENXUAN12316 小时前
最大子矩阵和:从 O(n⁴) 到 O(n³) 的列压缩 + Kadane
c语言·前端
H.莓飛17 小时前
【C++】【STL】vector_OJ题
linux·服务器·开发语言·数据结构·c++·visual studio
Rabitebla17 小时前
【Linux操作系统】进程篇(十一):进程程序替换——从底层原理到 exec 函数族
linux·服务器·c++·笔记·学习·算法