0
votes

I am new to C++ and I am learning to use boost::asio for network programming to processing incoming binary data. I come from embedded C where I would write packers and unpackers for the bits and byte received from the network socket using fixed buffer reads.

I want to learn about iostreams. To read binary data from the network socket in boost::asio I am using streambuf.

Is it possible to develop an iostream that reads data types from the stream and consume them?

Is the correct approach to subclass from std::basic_streambuf? Then consume the data from the stream using my data types. I would not need to define fixed size buffers to perform reads.

I cannot quite get my head around how to do it. Could some point to a suitable example of what I need to do.

I am doing this primarily as a learning experience to improve my C++ skills?

Thanks

Densha

1

1 Answers

0
votes

Don't subclass asio::streambuf.

Instead, use either streamable types or e.g. Boost Serialization archives (boost::archive::text_oarchive and boost::archive::text_iarchive) or somesuch. This is quite highlevel and allows you serialize complete object graphs, including polymorphic types and (cyclic) relations.

Sadly, Boost Serialization doesn't afford a simple framing protocol so either your protocol should expect new connections for each message or add a framing protocol on top of it.

There are many samples. Start here, perhaps:

PS. Be aware of other options

  • much simpler POD approaches with boost::asio::buffer directly
  • cereal, Cap'n-Proto, protobuf etc.