Reputation: 113
I am new to boost, I want to send a udp packet with multiple data type values. for example I want to send a packet of three bytes, in which first two bytes are used for message code and the last one is used for service id. I've used memcpy for this purpose, but the resultant buffer does not contain correct and desired values. Here is my code.
char buff[3];
uint16_t msgCode = 23;
char serviceId = '9';
msgCode = htons(msgCode);
memcpy(buff, &msgCode, 2);
memcpy(buff+2, &serviceId, 1);
std::string data = buff;
boost::shared_ptr<std::string> message(new std::string(data));
sock.async_send_to(boost::asio::buffer(data),dest_endPoint
, boost::bind(&udp_class::handle_send, this, message, boost::asio::placeholders::error
, boost::asio::placeholders::bytes_transferred));
Note: I've problems only in the buffer, I mean how to insert values of multiple types into the buffer and send as a udp packet.
thanx in advance.
Upvotes: 0
Views: 425
Reputation: 8660
I see a problem in the posted code. The data
variable is a local one and it is passed as the buffers
parameter of the async_send_to
method call. The boost::asio::buffer
class instance does not copy the data
content. In the moment when Asio sends data the data
variable is already destroyed. The documentation explains this behavior.
Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called.
To fix the problem, as far as I understand the code, is necessary to point the message
variable as the boost::asio::buffer
constructor parameter.
Upvotes: 1