当前位置:首页 > 编程笔记 > 正文
已解决

Ubuntu websocket程序

来自网友在路上 169869提问 提问时间:2023-11-10 08:23:36阅读次数: 69

最佳答案 问答题库698位专家为你答疑解惑

 转自:C/C++编程:WebSocketpp(Linux + Clion + boostAsio)_websocket++-CSDN博客

 目前自己使用的:

#include <functional>
#include <mutex>
#include <set>
#include <thread>
#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>typedef websocketpp::server<websocketpp::config::asio> server;
using websocketpp::connection_hdl;class count_server{
public:count_server(){m_server.init_asio();m_server.set_open_handler(bind(&count_server::on_open,this,websocketpp::lib::placeholders::_1));m_server.set_close_handler(bind(&count_server::on_close,this,websocketpp::lib::placeholders::_1));m_server.set_message_handler(bind(&count_server::on_message, this,websocketpp::lib::placeholders::_1,websocketpp::lib::placeholders::_2));}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 on_message(websocketpp::connection_hdl hdl, server::message_ptr msg) {std::cout<<"on_message called with hdl: "<<hdl.lock().get()<<" and message: "<<msg->get_payload()<<std::endl;}void count(){while (1){sleep(1);std::stringstream  ss;ss << "hello wotld!";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;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);
}

查看全文

99%的人还看了

相似问题

猜你感兴趣

版权申明

本文"Ubuntu websocket程序":http://eshow365.cn/6-37077-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!