Serialize and send a data structure using Boost?

后端 未结 7 1404
半阙折子戏
半阙折子戏 2020-12-02 10:45

I have a data structure that looks like this:

typedef struct
{
  unsigned short m_short1;
  unsigned short m_short2;
  unsigned char m_character;
} MyDataType;
         


        
7条回答
  •  生来不讨喜
    2020-12-02 11:22

    EDIT: I take back my answer below, what I proposed does have the time and space advantages over the stringstream solution but the asio::stream API is lacking some important functionality that will be needed in a long run (e.g. timed interruption).


    My original answer:

    Use streams from boost::asio, it has time and space advantages over writing it into std::stringstreams and then sending it in one go. Here is how:

    Client code:

    boost::asio::ip::tcp::iostream stream("localhost", "3000");
    
    if (!stream)
      throw std::runtime_error("can't connect");
    

    Server code:

    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint endpoint
      = boost::asio::ip::tcp::endpoint(ip::tcp::v4(), 3000);
    boost::asio::ip::tcp::acceptor acceptor(ios, endpoint);
    boost::asio::ip::tcp::iostream stream;
    
    // Your program stops here until client connects.
    acceptor.accept(*stream.rdbuf()); 
    

    And then, after you are connected with either client or server stream just do:

    MyDataType obj;
    
    // Send the object.
    boost::archive::text_oarchive archive(stream);
    archive << obj;
    
    // Or receive it.
    boost::archive::text_iarchive archive(stream);
    archive >> obj;
    

    You of course need to add the 'serialize' function into your MyDataType as Tymek wrote in his answer.

提交回复
热议问题