0

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

densha
  • 157
  • 3
  • 12

1 Answers1

0

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.
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Sehe - Wow thanks for the answer. I will read the examples and try to digest. For my specific case I am reading data from a device that I don't own. It has a binary protocol like. . The variable length data is decoded differently depending on the function code (FC). Which of these approaches would be best to investigate. – densha Jan 22 '18 at 07:22
  • Huh. Why was that information not in the question? A lot of unfounded stuff about "subclassing" (?!) streambuf, but nothing about simple requirements that you... _did_ know? I suggest you edit the question, and then implement it in the simplest way - using any buffers (streambuf or (fixed) vector of uint8_t). Streams are really not related here, you can use a stream on top off an array (`boost::iostreams::array_source` e.g.) just fine. – sehe Jan 22 '18 at 07:42