websocket服務器主要包含: (1) 設置日誌級別
(2) 初始化asio
(3) 設置默認Handler
(4) 進行監聽listen() 和 接收連接 start_accept()
(5) 調用run()
// The ASIO_STANDALONE define is necessary to use the standalone version of Asio.
// Remove if you are using Boost Asio.
// #define ASIO_STANDALONE
// 不使用TLS
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
// 使用TLS
// #include <websocketpp/config/asio.hpp>
// #include <websocketpp/server.hpp>
#include <functional>
typedef websocketpp::server<websocketpp::config::asio> server;
class utility_server {
public:
utility_server() {
// 設置日誌級別
m_endpoint.set_error_channels(websocketpp::log::elevel::all);
m_endpoint.set_access_channels(websocketpp::log::alevel::all ^ websocketpp::log::alevel::frame_payload);
// 初始化asio
m_endpoint.init_asio();
// 設置默認接收消息響應Hanlder
m_endpoint.set_message_handler(std::bind(&utility_server::echo_handler, this,
std::placeholders::_1,
std::placeholders::_2));
}
void echo_handler(websocketpp::connection_hdl hdl, server::message_ptr msg) {
// 發送數據
m_endpoint.send(hdl, msg->get_payload(), msg->get_opcode());
}
void run() {
// Listen on port 9002
m_endpoint.listen(9002);
// Queues a connection accept operation
m_endpoint.start_accept();
// Start the Asio io_service run loop
m_endpoint.run();
}
private:
server m_endpoint;
};
int main() {
utility_server s;
s.run();
return 0;
}