Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing struct in Boost Asio buffer

I'm looking for a way to send a packet made of a custom data structure through a socket with Boost Asio. At the moment I understand that you can send a string with the standard boost asio buffer (in the method boost::asio::write(..) ).

Is it possible to, for example, send the data from a filled in struct to the server or to a client? If yes, how do I need to do that because I can't find documentation about this.

like image 644
Dries Avatar asked Apr 04 '14 17:04

Dries


2 Answers

You can just copy POD objects bitwise.

In fact, Asio accepts boost/std array<T, N>, T[] or vector<T> buffers as long as T is a POD struct.

  • http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/overview/core/buffers.html
  • http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/buffer.html for the various constructors for mutable/const buffer sequence wrappers.

Otherwise, you could use Boost Serialization to serialize your data.

Finally, there's some support for binaries (binary dwords (big-endian/little-endian), binary floats) in Boost Spirit.

Update Example:

#include <memory>
#include <boost/asio.hpp>

int main()
{
    struct { float a, b; } arr[10];

    auto mutable_buffer = boost::asio::buffer(arr);
}

See it Live On Coliru

like image 85
sehe Avatar answered Oct 19 '22 12:10

sehe


You can also use Protocol Buffers for that purpose, not hard in configuring

https://code.google.com/p/protobuf/

like image 1
INait Avatar answered Oct 19 '22 13:10

INait