Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have trouble reading a vector from boost asio buffer. I have this vector:

 std::vector<float> points;

And I send it with boost asio write

  boost::asio::write (socket, boost::asio::buffer(&new_buffers->points.front(), nr_points * 3 * sizeof (float)));

On the other end I have:

std::vector<float> recv_vector;
tcp_socket.async_read_some(boost::asio::buffer(recv_vector), read_handler);

When I do recv_vector.size(), its always empty.

Can somebody tell me what I am doing wrong?

Marek

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
566 views
Welcome To Ask or Share your Answers For Others

1 Answer

Asio is not a serialization library. It does not serialize random vectors (you could use Boost Serialization for that).

It merely treats your buffer as the data buffer for the IO operation. So, e.g. in the second instance:

std::vector<float> recv_vector;
tcp_socket.async_read_some(boost::asio::buffer(recv_vector), read_handler);

you tell it to receive the amount of data that fits into the POD buffer represented by the vector recv_vector, which is empty. You are therefore telling Asio to receive 0 bytes, which I presume it will do happily for you.

To fix things, either use serialization (putting the responsibility in the hands of another library) or manually send the size of the vector before the actual data.

Full Demo

I have more explanations and a full sample here: How to receive a custom data type from socket read?

Note, as well, that you don't have to do that complicated thing:

boost::asio::write (socket, boost::asio::buffer(&new_buffers->points.front(), nr_points * 3 * sizeof (float)));

Instead, for POD type vectors, just let Asio do the calculations and casts:

boost::asio::write (socket, buffer(new_buffers->points));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...