The most commonly used protocol for sending data over a TCP
socket like you propose is HTTP.
In HTTP
, the body size is sent as a string in the relevant header [request, response or chunk] with special characters (\r\n
for a request or response, ;
for a chunk) to identify the end of the size string.
You'll need to decide on your own special character; NULL
would be the easiest for null terminated strings.
One of the key issues of sending data as you propose, is that TCP
can split the data up into a number of (what are commonly called) packets
, so the receiver may not receive the whole of your Packet
at once.
BTW Packet
is a poor name in this context.
You don't need to know the size of your complete Packet
before you send it. You can call boost:asio
async_write with a collection of const_buffers to send both the Header
and Body
of your Packet
.
On the receive side, I recommend using async_read_some with a string
buffer large enough for your whole Packet
including the Header
string.
You should be able to read the Body
size from the characters before the NULL
and calculate your Packet
size from the Body
size plus the number of characters before the NULL
+ 1 (for the NULL
). If this is less that the size reported by your ReadHandler then your Body
has been split across multiple TCP
packets
, so you'll need to receive the other packets
to reconstruct your Packet
Body
.
Or, you could save yourself the trouble and simply use a tried and tested HTTP
library like via-httplib or boost::beast.