一、环境
环境:银河麒麟(ubuntu内核)
依赖:boost_1_75_0、websocketpp
二、下载地址
#boost
https://www.boost.org/users/history/version_1_75_0.html
#websocketpp
https://github.com/zaphoyd/websocketpp
三、boost安装
1、解压boost
2、sudo ./bootstrap.sh
3、sudo ./b2 install
4、安装后的内容确认
cd /usr/local/include/boost
四、websocketpp安装
1、cmake CMakeLists.txt
2、sudo make
3、sudo make install
4、安装后的内容确认
cd /usr/local/include/websocketpp
五、socket的服务器端程序(使用websocketpp中自带的simple_broadcast_server例子即可)
#include <set>
#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;
using websocketpp::lib::bind;
class broadcast_server {
public:
broadcast_server() {
m_server.init_asio();
m_server.set_open_handler(bind(&broadcast_server::on_open,this,::_1));
m_server.set_close_handler(bind(&broadcast_server::on_close,this,::_1));
m_server.set_message_handler(bind(&broadcast_server::on_message,this,::_1,::_2));
}
void on_open(connection_hdl hdl) {
m_connections.insert(hdl);
}
void on_close(connection_hdl hdl) {
m_connections.erase(hdl);
}
void on_message(connection_hdl hdl, server::message_ptr msg) {
// 服务器端收到的信息,循环发送给所有连接的客户端
for (auto it : m_connections) {
m_server.send(it,msg);
}
}
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;
};
int main() {
broadcast_server server;
server.run(9002);
}
六、使用postman测试一下接口
#新建WebSocket Request请求(多建几个客户端发送消息后,其他端都可以收到)
ws://xx.xx.xx.xx:9002