boost asio 写/读向量

时间:2023-05-08
本文介绍了boost asio 写/读向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我无法从 boost asio 缓冲区读取向量.我有这个向量:

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

 std::vector<float> points;

我用 boost asio write 发送

And I send it with boost asio write

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

另一方面,我有:

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

当我执行 recv_vector.size() 时,它总是空的.

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

谁能告诉我我做错了什么?

Can somebody tell me what I am doing wrong?

马雷克

推荐答案

Asio 不是序列化库.它不会序列化随机向量(你可以使用 Boost Serialization).

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

它只是将您的缓冲区视为 IO 操作的数据缓冲区.所以,例如在第二种情况下:

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);

您告诉它接收适合由向量 recv_vector 表示的 POD 缓冲区的数据量,该向量为空.因此,您是在告诉 Asio 接收 0 字节,我认为它会为您带来快乐.

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.

我在这里有更多解释和完整示例:如何从套接字读取中接收自定义数据类型?

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)));

相反,对于 POD 类型向量,只需 让 Asio 进行计算和转换:

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

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

这篇关于boost asio 写/读向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:错误:'i' 没有用 auto 命名类型 下一篇:如何将 std::string 复制到 std::vector<char> 中?

相关文章