如何使用 boost::asio 发送大对象
再会。
我使用 boost::asio 通过网络接收一个大对象。
我有一个代码:
for (int i = 1; i <= num_packets; i++)
boost::asio::async_read(socket_, boost::asio::buffer(Obj + packet_size * (i - 1), packet_size), boost::bind(...));
Where My_Class * Obj
。 我怀疑这种方法是否可行(因为我这里有一个指向对象的指针)?或者如何使用固定大小(以字节为单位)的数据包接收该对象会更好?
提前致谢。
Good day.
I'm receiving a large objects via the net using boost::asio.
And I have a code:
for (int i = 1; i <= num_packets; i++)
boost::asio::async_read(socket_, boost::asio::buffer(Obj + packet_size * (i - 1), packet_size), boost::bind(...));
Where My_Class * Obj
.
I'm in doubt if that approach possible (because i have a pointer to an object here)? Or how it would be better to receive this object using packets of fixed size in bytes?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为 boost.asio 文档中的 http_client 示例比我能更好地解释它:
http://www. boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/http/client/async_client.cpp
你不需要担心数据包,你会得到一个 TCP 流,然后从属于流的套接字。故事结束。
您需要这样的东西,不同之处在于您不会将响应读取到 std::cout 中,而是从中重建对象(不确定这是否适用于对象,或者仅适用于简单类型)。
您还应该研究序列化,例如 Boost.Serialization。
如果您想传输复杂的对象,这绝对没有坏处。
I think the http_client example in boost.asio documentation explains it better than I can:
http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/example/http/client/async_client.cpp
You won't need to bother about packets, you get a TCP stream, and you read from the socket belonging to the stream. End of story.
You need something like this, the difference is that you won't be reading the response into std::cout, but rebuilding your object from it (not sure if this works for objects, or just simple types).
You should also look into serialization, for example Boost.Serialization.
That never hurts if you want to transfer complex objects.