Reputation: 4670
I was reading the UDP daytime example
from boost asio tutorial. It uses a recv_buffer_
and uses async_receive_from()
to run the receiving loop.
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
What I don't understand is
boost::array<char, 1> recv_buffer_;
why its size is one ? what if the message received in more than one byte long ?
EDIT
as @Guy Sirton pointed I missed hsi part which was written in that page.
Since we only provide the 1-byte recv_buffer_ to contain the client's request, the io_service object would return an error if the client sent anything larger. We can ignore such an error if it comes up.
But is there anyway to read the entire message without having a buffer size ? like looping receive_some
by each character and storing in a string ?
Upvotes: 0
Views: 2898
Reputation: 51871
A buffer size is required.
UDP preserves message boundaries. When data is read from a socket, it will read up to the message boundary, even if the size of the provided buffer is smaller than the message. When the message size is larger than that of the buffer, the error code will be set to boost::asio::error::message_size
.
Either allocate a buffer large enough to read the maximum expected message size or use reactor-style operations to lazily allocate the buffer.
Upvotes: 3