websocket++序列: Server

送分小仙女□ 提交于 2020-04-13 17:01:20

【今日推荐】:为什么一到面试就懵逼!>>>

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;
}

 

发布了211 篇原创文章 · 获赞 109 · 访问量 32万+
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!