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);
}
相关推荐
2401_838472514 分钟前
单元测试在C++项目中的实践
开发语言·c++·算法
naruto_lnq10 分钟前
移动语义与完美转发详解
开发语言·c++·算法
赤水无泪34 分钟前
04 C++语言---运算符和符号
开发语言·c++
定偶43 分钟前
USB协议
c语言·网络·数据库
从此不归路44 分钟前
Qt5 进阶【10】应用架构与插件化设计实战:从「单体窗口」走向「可扩展框架」
开发语言·c++·qt·架构
瓦特what?44 分钟前
C++编程防坑指南(小说版)
android·c++·kotlin
sjjhd6521 小时前
C++模拟器开发实践
开发语言·c++·算法
二年级程序员1 小时前
qsort函数的使用与模拟实现
c语言·数据结构·算法·排序算法
Queenie_Charlie1 小时前
素数(线性筛法)
c++·线性筛法·质数·简单数论
莹莹学编程—成长记1 小时前
TCP/IP五层模型+网络传输基本流程
网络·c++