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;
}
来源:oschina
链接:https://my.oschina.net/u/4294583/blog/3233047