Search code examples
c++boost-asioboost-serialization

Boost serialization with boost socket fails


I'm trying to un-serialize an object passed trough an asio socket but I'm having an error : "terminate called after throwing an instance of 'boost::archive::archive_exception' what(): input stream error" when I'm trying to get the data:

server side :

int main()
{
...
    std::ostringstream oss;
    Note note(20,20);

    boost::archive::text_oarchive oa(oss);
    oa << note;
    std::cout << (char*)&oa << std::endl;
    send_(socket_, (char *)&oa);
}

client side :

int main()
{
...
    boost::asio::read(socket, receive_buffer, boost::asio::transfer_all(), error);

    std::string myString;

    std::istream(&receive_buffer) >> myString;
    std::istringstream iss(myString);
    boost::archive::text_iarchive ia(iss); <--- input stream error
    ia >> note;
    std::cout << note.denominateur << std::endl;
}

Solution

  • You have to send the content of ostringstream i.e. string which contains serialized Note. Now you are sending bytes of text_oarchive instance, which doesn't make any sense for me.

    It may look like:

      boost::archive::text_oarchive oa(oss);
      oa << note;
      cout << oss.str(); // HERE you get some string which represents serialized Note
      // and content of this string should be sent
      send_(socket_, oss.str().c_str(), oss.str().size());
                     ^^^ content        ^^^ size of content
    

    Your send_ function takes no size parameter? Interesting, for me it should take this param to know how many bytes must be transmitted.

    Regarding to the client side:

    // [1]
    boost::asio::read(socket, receive_buffer, boost::asio::transfer_all(), error);
    

    because you didn't provide MCVE, I assume in [1] line you create receive_buffer as some kind of dynamic_buffer, if not and it is just empty string you will read empty string. So deserialization won't work.