Asio::streambuf is a handy class for chunking up data.
Otherwise: not only is UDP message-oriented, it is also unreliable, i.e., packets can be lost [1], duplicated or delivered out-of-order. Thus you need to design an application-level protocol to handle UDP transfers. There are no tools in Boost to help with this.
[1] Deciding on whether a packet is lost usually calls for a timer.
From: Boost-users On Behalf Of Álvaro Cebrián Juan via Boost-users
Sent: Monday, June 11, 2018 1:58 PM
To: boost-users@lists.boost.org
Cc: Álvaro Cebrián Juan
Subject: [Boost-users] Serialization over UDP
Hello everyone,
I have no prior experience with Boost. I need to serialize an object and send it over UDP to a remote machine. I already have a completely functional serialization mechanism over TCP and I would like to convert it to UDP.
The member function that I use to serialize the objects over TCP looks like this:
/// Asynchronously write a data structure to the socket.
template
void async_write(const T& t, Handler handler)
{
// Serialize the data first so we know how large it is.
std::ostringstream archive_stream;
boost::archive::text_oarchive archive(archive_stream);
archive << t;
outbound_data_ = archive_stream.str();
// Format the header.
std::ostringstream header_stream;
header_stream << std::setw(header_length)
<< std::hex << outbound_data_.size();
if (!header_stream || header_stream.str().size() != header_length)
{
// Something went wrong, inform the caller.
boost::system::error_code error(boost::asio::error::invalid_argument);
socket_.get_io_service().post(boost::bind(handler, error));
return;
}
outbound_header_ = header_stream.str();
// Write the serialized data to the socket. We use "gather-write" to send
// both the header and the data in a single write operation.
std::vectorboost::asio::const_buffer buffers;
buffers.push_back(boost::asio::buffer(outbound_header_));
buffers.push_back(boost::asio::buffer(outbound_data_));
boost::asio::async_write(socket_, buffers, handler);
}
As you can see in the code, it makes use of streams to write the serialized data asynchronously to the remote machine. This is fine for TCP, since this protocol is stream-oriented.
However, as far as I know, this does not work for UDP because it is message-oriented and therefore it does not support streams.
Thus, I would be very grateful if someone could shed some light on which tools does Boost provide that would make serialization feasible over UDP.
Thank you.
Best Regards,
Álvaro