...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Non-trivial algorithms need to do more than send entire messages at once, such as:
These tasks may be performed by using the serializer stream interfaces. To use these interfaces, first construct an appropriate serializer from the message to be sent:
Table 1.15. Serializer
Name |
Description |
---|---|
/// Provides buffer oriented HTTP message serialization functionality. template< bool isRequest, class Body, class Fields = fields > class serializer; |
|
/// A serializer for HTTP/1 requests template< class Body, class Fields = fields > using request_serializer = serializer<true, Body, Fields>; |
|
/// A serializer for HTTP/1 responses template< class Body, class Fields = fields > using response_serializer = serializer<false, Body, Fields>; |
The choices for template types must match the message passed on construction. This code creates an HTTP response and the corresponding serializer:
response<string_body> res; response_serializer<string_body> sr{res};
The stream operations which work on serializers are:
Table 1.16. Serializer Stream Operations
Name |
Description |
---|---|
Send everything in a |
|
Send everything in a |
|
Send only the header from a |
|
Send only the header from a |
|
Send part of a |
|
Send part of a |
Here is an example of using a serializer to send a message on a stream synchronously.
This performs the same operation as calling write(stream, m)
:
/** Send a message to a stream synchronously. @param stream The stream to write to. This type must support the @b SyncWriteStream concept. @param m The message to send. The Body type must support the @b BodyWriter concept. */ template< class SyncWriteStream, bool isRequest, class Body, class Fields> void send( SyncWriteStream& stream, message<isRequest, Body, Fields> const& m) { // Check the template types static_assert(is_sync_write_stream<SyncWriteStream>::value, "SyncWriteStream requirements not met"); static_assert(is_body_writer<Body>::value, "BodyWriter requirements not met"); // Create the instance of serializer for the message serializer<isRequest, Body, Fields> sr{m}; // Loop until the serializer is finished do { // This call guarantees it will make some // forward progress, or otherwise return an error. write_some(stream, sr); } while(! sr.is_done()); }