gpt4 book ai didi

c++ - 使用一个TCP套接字的多个请求

转载 作者:行者123 更新时间:2023-12-02 10:09:57 25 4
gpt4 key购买 nike

我正在学习套接字编程(和C++)。我写了一个下面的函数,要求一个数组的总和(使用boost库):

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();
});
}
第一次写入和读取都可以正常工作,但是第二次进入循环写入套接字可以正常工作,但是读取时出现错误:

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


此错误与我的机器有关吗?我应该怎么做才能做到这一点?

最佳答案

您似乎正在尝试从服务器接收所有数据:

boost::asio::streambuf receiveBuffer;
boost::asio::read(_socket, receiveBuffer, boost::asio::transfer_all(), err);
read()命令完成的唯一方法是服务器指示流的结尾。由于您是第一次收到有效的响应,这意味着服务器在向您发送响应后立即关闭了连接。

关于c++ - 使用一个TCP套接字的多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64069424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com