boost asio write/read vector

前端 未结 1 865
夕颜
夕颜 2020-12-04 03:49

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

 std::vector points;

And I send it with boost asio

相关标签:
1条回答
  • 2020-12-04 04:27

    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));
    
    0 讨论(0)
提交回复
热议问题