forked from boostorg/beast
78 lines
2.2 KiB
Plaintext
78 lines
2.2 KiB
Plaintext
|
|
[/
|
||
|
|
Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
|
||
|
|
|
||
|
|
Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||
|
|
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||
|
|
]
|
||
|
|
|
||
|
|
[section:messages Send and Receive Messages]
|
||
|
|
|
||
|
|
After the WebSocket handshake is accomplished, callers may send and receive
|
||
|
|
messages using the message oriented interface. This interface requires that
|
||
|
|
all of the buffers representing the message are known ahead of time:
|
||
|
|
```
|
||
|
|
template<class NextLayer>
|
||
|
|
void echo(websocket::stream<NextLayer>& ws)
|
||
|
|
{
|
||
|
|
multi_buffer b;
|
||
|
|
websocket::opcode::value op;
|
||
|
|
ws.read(op, b);
|
||
|
|
|
||
|
|
ws.set_option(websocket::message_type{op});
|
||
|
|
ws.write(b.data());
|
||
|
|
b.consume(b.size());
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
[important
|
||
|
|
Calls to [link beast.ref.websocket__stream.set_option `set_option`]
|
||
|
|
must be made from the same implicit or explicit strand as that used
|
||
|
|
to perform other operations.
|
||
|
|
]
|
||
|
|
|
||
|
|
[heading Frames]
|
||
|
|
|
||
|
|
Some use-cases make it impractical or impossible to buffer the entire
|
||
|
|
message ahead of time:
|
||
|
|
|
||
|
|
* Streaming multimedia to an endpoint.
|
||
|
|
* Sending a message that does not fit in memory at once.
|
||
|
|
* Providing incremental results as they become available.
|
||
|
|
|
||
|
|
For these cases, the frame oriented interface may be used. This
|
||
|
|
example reads and echoes a complete message using this interface:
|
||
|
|
```
|
||
|
|
template<class NextLayer>
|
||
|
|
void echo(websocket::stream<NextLayer>& ws)
|
||
|
|
{
|
||
|
|
multi_buffer b;
|
||
|
|
websocket::frame_info fi;
|
||
|
|
for(;;)
|
||
|
|
{
|
||
|
|
ws.read_frame(fi, b);
|
||
|
|
if(fi.fin)
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
ws.set_option(websocket::message_type{fi.op});
|
||
|
|
consuming_buffers<
|
||
|
|
multi_buffer::const_buffers_type> cb{b.data()};
|
||
|
|
for(;;)
|
||
|
|
{
|
||
|
|
using boost::asio::buffer_size;
|
||
|
|
std::size_t size = std::min(buffer_size(cb));
|
||
|
|
if(size > 512)
|
||
|
|
{
|
||
|
|
ws.write_frame(false, prepare_buffers(512, cb));
|
||
|
|
cb.consume(512);
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
ws.write_frame(true, cb);
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
[endsect]
|