mardi 24 novembre 2015

std::istream : limit the length of readable data before EOF?

I use a lib (gsoap) that take an input stream and read it until end of stream is reached. My problem is in my case the input stream a boost::asio::ip::tcp::iostream, and the socket is not closed as the client wait for a response, and so EOF never appends.

I know the length of the content to read (in fact my socket is a very basic http implementation and I read the content length), so my idea is to have a decorator that encapsulate the socket istream but that sends EOF after N bytes are read.

Is this kind of pattern possible and easy (I'm a java developer, not a c++ one) ? Or maybe there is a better possibility ?

The actual method I use is to user read(char[] buff, length) and then create a std::string, and then create a istringstream and pass it to gsoap. This is very inefficient (content is stored multiple (3) times in memory), but it works :

ns_mytype* read(std::istream& input, unsigned int length) {
    char* s = new char[length];
    input.read(s, length);
    std::string str(s, input.gcount());
    std::istringstream stream(str);

    ns_mytype* model = soap_new_ns__mytype(&soap);
    if (soap_read_ns__mytype(&soap,model) != SOAP_OK) {
        delete s;
        throw soap.error;
    }
    delete s;
    return model;
}

Thank you for reading

Aucun commentaire:

Enregistrer un commentaire