websocketbeast-websockets

How to set subprotocol with boost weboscket


I want to use the subprotocol with boost websocket.

For example, I have s websocket server address , ws://127.0.0.1:5005. Now I want to replace it with ws://127.0.0.1:5005/order. "order" is the subprotocol in websocket, which could be used in libwebsocket. I find no resource about subprotocol with boost.


Solution

  • Here is a way to set subprotocol for Websocket in Boost:

    if the Boost version >= 1.7.0, then: Click here for more detail

    stream<tcp_stream> ws(ioc);
    ws.set_option(stream_base::decorator(
    [](request_type& req)
    {
        // Set the client field on the request
        req.set(boost::beast::http::field::sec_websocket_protocol, "protoo");
        req.set(boost::beast::http::field::sec_websocket_version, "13");
        req.set(boost::beast::http::field::sec_websocket_extensions,
                "xxx");
    }));
    

    else: Click here for more detail

    stream<tcp_stream> ws(ioc);
    ws.handshake_ex("ws://127.0.0.1:5005", "/",
    [](request_type& req)
    {
        req.insert(boost::beast::http::field::sec_websocket_protocol, "protoo");
        req.insert(boost::beast::http::field::sec_websocket_version, "13");
        req.insert(boost::beast::http::field::sec_websocket_extensions,
                "xxx");
    });