c++ – Boost Asio corrupted buffer

I send requests to the server using the read function, but when receiving data, third-party data appears in the buffer, and this only appears on the server, but everything is fine on the home PC, here is the code for sending the request.

std::string send(std::string _hostName, std::string _rawRequest, std::string _ipAddress = "default") {
    boost::system::error_code ec;
    boost::asio::ip::tcp::resolver resolver(_IoContext);
    boost::asio::ssl::context ssl_context = boost::asio::ssl::context(boost::asio::ssl::context::sslv23_client);
    boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket(_IoContext, ssl_context);

    try {
        boost::asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(_hostName, "https", ec);
        if (ec) throw std::exception(ec.what().c_str());

        socket.lowest_layer().open(boost::asio::ip::tcp::v4(), ec);
        if (ec) throw std::exception(ec.what().c_str());

        if (_ipAddress != "default") {
            socket.lowest_layer().bind(boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4::from_string(_ipAddress), 0), ec);
            if (ec) throw std::exception(ec.what().c_str());
        }

        socket.lowest_layer().connect(*endpoints, ec);
        if (ec) throw std::exception(ec.what().c_str());

        socket.handshake(boost::asio::ssl::stream_base::client, ec);
        if (ec) throw std::exception(ec.what().c_str());

        boost::asio::streambuf buffer;
        std::ostream buffer_stream(&buffer);
        buffer_stream << _rawRequest;
        boost::asio::write(socket, buffer, ec);
            if (ec) throw std::exception(ec.what().c_str());

        boost::asio::streambuf response;
        boost::asio::read(socket, response, boost::asio::transfer_all(), ec);

        boost::asio::streambuf::const_buffers_type response_buffer = response.data();
        std::string response_str = boost::asio::buffer_cast<const char*>(response.data());

        socket.shutdown(ec);
        socket.lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
        socket.lowest_layer().cancel(ec);
        socket.lowest_layer().close();

        return response_str;
    } catch (std::exception& e) {
        throw std::exception(std::format("{} from {}", e.what(), _ipAddress).c_str());
    }
}

I tried to do different buffer conversions, and changed the arguments in the read function a little, but nothing helped.

Read more here: Source link