I'm new to socket programming and c++. I have a the following method that sends an array to server and receives sum of the array, I tried to make it async.
std::future<void> AsyncClient::ReqSum(const std::vector<double>& numbers)
{
return std::async(
std::launch::async,
[&, numbers]()
{
// Setup connection. Can move to seperate method?
boost::asio::io_service _ioservice;
tcp::socket _socket(_ioservice);
_socket.connect(m_endpoint);
std::string requestJson = Serializer::ArraySumRequest(numbers);
boost::system::error_code err;
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();
});
}
Actually I want to know is it possible to use one connection to for multiple requests(i.e move that socket and connection to another method)?
And if there are any fixes to my code please let me know.