c++booststreamboost-asiobinarystream

Read Binary Data over TCP with Boost::Asio


My program receives binary data over a TCP-Connection. The connection is established using the boost::asio library. After reading the stream I need to return the received data as char*-Array. This is what I've got so far:

char* read()
    {
        boost::system::error_code ec;

        boost::asio::streambuf response;
        size_t bytes = boost::asio::read(this->socket_, response, ec);

        if(ec.value() != boost::system::errc::success)
        {
            cout << "In " << BOOST_CURRENT_FUNCTION << ": " << ec.category().name() << ':' << ec.value() << endl;
            return "";
        }

        std::istream stream(&response);

        char* ret = new char[bytes]{0};
        int i = 0;
        while(!stream.eof())
        {
            // ..??.. Write into char array
            i++;
        }
    }

I'm looking for a function to write the received binary-data into the char-array.


Solution

  • You can use read for example.

    stream.read(ret, bytes);
    

    or you can use sgetn

    response.read(ret, bytes);
    

    or you can use any other thing.