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);
}
相关推荐
SNAKEpc121381 小时前
Qt开源控件库(qt-material-widgets)的编译及使用
c++·qt·开源
于慨2 小时前
计算机考研C语言
c语言·开发语言·数据结构
轩宇^_^3 小时前
C++ 类与对象的实际应用案例详解
开发语言·c++
c7_ln4 小时前
编程视界:C++命名空间
开发语言·c++·笔记
十五年专注C++开发4 小时前
SQLiteStudio:一款免费开源跨平台的SQLite管理工具
数据库·c++·qt·sqlite
Serendipity-Solitude4 小时前
c++中的数学函数库(少)
开发语言·c++
坚定学代码4 小时前
PIMPL模式
c++
imgsq5 小时前
已安装 MFC 仍提示“此项目需要 MFC 库”的解决方法 (MSB8041)
c++·mfc
香菇滑稽之谈5 小时前
责任链模式的C++实现示例
开发语言·c++·设计模式·责任链模式