0

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.

4

1 回答 1

1

我在发布的代码中看到了一个问题。该data变量是本地变量,它作为方法调用的buffers参数传递。async_send_toboost::asio::buffer实例不复制data内容。在 Asio 发送数据的那一刻,data变量已经被销毁。文档解释了这种行为。

尽管缓冲区对象可以根据需要被复制,但底层内存块的所有权由调用者保留,它必须保证它们在调用处理程序之前保持有效。

要解决这个问题,据我了解代码,有必要将message变量指向boost::asio::buffer构造函数参数。

于 2013-06-12T09:39:11.097 回答