从关闭消息中检索代码/原因

时间:2015-03-12 16:00:25

标签: websocket++

我想从关闭消息中检索代码和原因。我已经使用set_close_handler注册了一个处理程序,但是没有获得有效负载。另外,我找到了websocketpp::close::extract_codewebsocketpp::close::extract_reason,它们获取有效载荷并返回相关部分。关闭的有效负载是否存储在某处? connection_ptr中的最后一个代码/原因是否可用?

1 个答案:

答案 0 :(得分:1)

为此,连接对象有两种访问方法:

close::status::value get_remote_close_code() const;
std::string const & get_remote_close_reason() const;

使用connection_hdl调用on_close方法,因此需要调用get_con_from_hdl()来获取指向连接的指针。这是一个例子:

void chat_server::on_close(connection_hdl hdl) {
    try {
        server::connection_ptr cp = m_server.get_con_from_hdl(hdl);
        websocketpp::close::status::value ccode = cp->get_remote_close_code();
        std::cout << "Closed connection. code " << ccode << " ["
            << cp->get_remote_close_reason() << "]" << std::endl;
    } catch (const websocketpp::lib::error_code& e) {
        std::cout << __func__ << " failed because: " << e << "(" << e.message() << ")"
             << std::endl;
    } catch (std::exception& e) {
        std::cout << e.what() << std::endl;
    }
}