websocket++

Retrieve the code/reason from a close message


I would like to retrieve the code and reason from a close message. I have registered a handler with set_close_handler, but that doesn't get a payload. Separately, I have found websocketpp::close::extract_code and websocketpp::close::extract_reason which take a payload and return the relevant pieces. Is the close payload stored somewhere? Are the last code/reason available in the connection_ptr?


Solution

  • The connection object has two accessor methods for this purpose:

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

    The on_close method is called with a connection_hdl, so you need to call get_con_from_hdl() to obtain a pointer to the connection. Here's an example:

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