Search code examples
c++socketsostream

How to send ostream by socket in C++?


I am trying to send ostream which contains binary data by socket in C++.

I'm using Microsoft SEAL for developing about encryption.
Now I need to send a ciphertext from client to server. Microsoft SEAL provides a function

void Ciphertext::save(ostream &stream) const

to serialize the Ciphertext object to ostream, but after calling

void Ciphertext::save(ostream &stream) const,

I have no idea how to send the ciphertext (which is in ostream) by socket in client (of course also have no idea how to receive in server).

I tried the solution, but it seems that it could not work when the data is binary data.

I would like to know how to write the code of sending ostream in client and receiving in server. Thank you.


Solution

  • You can pass it ostringstream to fill and the extact the string containing binary data from it:

    #include <sstream>
    #include <string>
    // ...
    std::string save_into_string(Ciphertext const& ciphertext) {
        std::ostringstream s;
        ciphertext.save(s);
        return s.str();
    }