5
votes

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.

3
@AndrewBarber lol @ closing this question - I don't fully agree it's too broad per se (it's tagged boost-asio after all, and mentions he knows how to use boost asio buffer). My answer links to the parts of the documentation he couldn't find. But I see what you're missing - context and sample code :)sehe
@sehe Hmmm... sure, I see that. Reopening!Andrew Barber

3 Answers

6
votes

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.

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

1
votes

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

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

0
votes

here is some example which works for me:

void callback(STRUCT_A& s)
{
  f_strand.post(boost::bind(f, boost::asio::buffer(&s, sizeof(s))));
}

void f(boost::asio::mutable_buffers_1 v)
{
  STRUCT_A *a = boost::asio_buffer_cast<STRUCT_A*>(v);
}