Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of boost. Click here for the latest Boost documentation.
PrevUpHomeNext

Handshaking (Clients)

A WebSocket session begins when a client sends the HTTP/1 Upgrade request for websocket, and the server sends an appropriate response indicating that the request was accepted and that the connection has been upgraded. The Upgrade request must include the Host field, and the target of the resource to request. The stream member functions handshake and async_handshake are used to send the request with the required host and target strings.

ws.handshake("localhost", "/");

The implementation will create and send a request that typically looks like this:

Table 1.24. WebSocket Upgrade HTTP Request

Serialized Octets

Description

GET / HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: upgrade
Sec-WebSocket-Key: 2pGeTR0DsE4dfZs2pH+8MA==
Sec-WebSocket-Version: 13
User-Agent: Beast

The host and target parameters become part of the Host field and request-target in the resulting HTTP request. The key is generated by the implementation. Callers may add fields or modify fields by providing a decorator, described below.


Decorators

If the caller wishes to add or modify fields, the member functions handshake_ex and async_handshake_ex are provided which allow an additional function object, called a decorator, to be passed. The decorator is invoked to modify the HTTP Upgrade request as needed. This example sets a subprotocol on the request:

ws.handshake_ex("localhost", "/",
    [](request_type& m)
    {
        m.insert(http::field::sec_websocket_protocol, "xmpp;ws-chat");
    });

The HTTP Upgrade request produced by the previous call will look thusly:

Table 1.25. Decorated WebSocket Upgrade HTTP Request

Serialized Octets

Description

GET / HTTP/1.1
Host: localhost
Upgrade: websocket
Connection: upgrade
Sec-WebSocket-Key: 2pGeTR0DsE4dfZs2pH+8MA==
Sec-WebSocket-Version: 13
Sec-WebSocket-Protocol: xmpp;ws-chat
User-Agent: Beast

Undefined behavior results if the decorator modifies the fields specific to perform the WebSocket Upgrade , such as the Upgrade and Connection fields.


Filtering

When a client receives an HTTP Upgrade response from the server indicating a successful upgrade, the caller may wish to perform additional validation on the received HTTP response message. For example, to check that the response to a basic authentication challenge is valid. To achieve this, overloads of the handshake member function allow the caller to store the received HTTP message in an output reference argument of type response_type as follows:

response_type res;
ws.handshake(res, "localhost", "/");
if(! res.count(http::field::sec_websocket_protocol))
    throw std::invalid_argument("missing subprotocols");

PrevUpHomeNext