Abraham
Abraham

Reputation: 64

Multiple requests using one tcp socket

I'm learning socket programming(and c++). I wrote a function like below that requests for sum of an array(using boost library):

std::future<void> AsyncClient::ReqSum(const std::vector<double>& numbers)
{
    return std::async(
        std::launch::async,
        [&, numbers]()
        {
            // Setup connection.
            boost::asio::io_service _ioservice;
            tcp::socket _socket(_ioservice);
            _socket.connect(m_endpoint);

            std::string requestJson = Serializer::ArraySumRequest(numbers);
            boost::system::error_code err;
            while (true)
            {
                boost::asio::write(_socket, boost::asio::buffer(requestJson), err);
                if (err)
                {
                    std::stringstream ss;
                    ss << "Couldn't write to socket! error code: " << err;
                    throw ss.str();
                }

                // getting response from server
                boost::asio::streambuf receiveBuffer;
                boost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err);

                if (err && err != boost::asio::error::eof)
                {
                    std::stringstream ss;
                    ss << "Receiving from the server failed! error code: " << err.message();
                    throw ss.str();
                }

                const char* data = boost::asio::buffer_cast<const char*>(receiveBuffer.data());

                rapidjson::Document doc;
                doc.Parse<rapidjson::kParseDefaultFlags>(data);

                if (!doc.HasMember("result"))
                    throw "No result found!";

                double result = doc["result"].GetDouble();

                std::cout << "Sum of the array: " << result << std::endl;
            }
            _socket.shutdown(boost::asio::socket_base::shutdown_both);
            _socket.close();
        });
}

The first time writing and reading both work currectly but second time I get inside the loop writing to the socket works just fine but get the an error when reading:

error code: 10053; message: An established connection was aborted by the software in your machine host.

Is this error related to my machine? what should I do to make this?

Upvotes: 1

Views: 282

Answers (1)

G. Sliepen
G. Sliepen

Reputation: 7973

It looks like you are trying to receive all data from the server:

boost::asio::streambuf receiveBuffer;
boost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err);

The only way that read() commands finishes is if the server indicates the end of the stream. Since you are receiving a valid response the first time, that implies that the server closes the connection right after sending you the response.

Upvotes: 1

Related Questions