我目前正在尝试弄清楚如何正确重用 asio 套接字。我能够成功发出请求,并得到结果。第二次发出请求时,我得到一个异常:read_some: End of file。第二次写入似乎工作正常,我看到第二个 http 请求通过wireshark 发出。我认为套接字上的剩余信息会以某种方式破坏我的连接。对此问题的任何帮助将不胜感激。这是我正在使用的代码:
persistent_connection::persistent_connection(std::string ip, std::string port):
io_service_(), socket_(io_service_), is_setup_(false)
{
boost::asio::ip::tcp::resolver resolver(io_service_);
boost::asio::ip::tcp::resolver::query query(ip,port);
boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query);
boost::asio::ip::tcp::endpoint endpoint = *iterator;
socket_.async_connect(endpoint, boost::bind(&persistent_connection::handler_connect, this, boost::asio::placeholders::error, iterator));
io_service_.run();
}
void persistent_connection::handler_connect(const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator endpoint_iterator)
{
if(ec)
{
std::cout << "Couldn't connect" << ec << std::endl;
return;
}
else
{
boost::asio::socket_base::keep_alive keep_option(true);
socket_.set_option(keep_option);
}
}
void persistent_connection::write(std::string message)
{
std::string request_stream = "GET /" + message + " HTTP/1.0\r\n";
request_stream += "HOST: 10.1.10.220";
request_stream += "Accept: */*\r\n";
request_stream += "Connection: keep-alive\r\n\r\n";
try
{
boost::asio::write(socket_, boost::asio::buffer(request_stream, request_stream.size()));
}catch(std::exception& e)
{
std::cout << "Write exception: " << e.what() << std::endl;
}
boost::array<char,8192> buf;
try
{
socket_.read_some(boost::asio::buffer(buf));
}catch(std::exception& e)
{
std::cout << "Read exception: " << e.what() << std::endl;
}
std::string response = buf.data();
std::cout << response << std::endl;
}
编辑:添加了主要功能。
int main()
{
persistent_connection p("10.1.10.220", "80");
std::string check;
do
{
std::cin >> check;
if(check.compare("s") == 0)
{
std::cout << "Sending" << std::endl;
p.write("100");
}
}while(check.compare("x") != 0);
}