0

我目前正在尝试弄清楚如何正确重用 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);
}
4

1 回答 1

3

您在尝试时遇到此异常的事实read_some意味着 HTTP 服务器在第一个请求结束后关闭连接,即服务器忽略“Connection: keep-alive”标头(请注意,HTTP 1.0 服务器不一定支持持久连接) .

但是,在 1.1 版本中,默认情况下连接是持久的,因此请求“HTTP/1.1”应该可以解决这个问题。

于 2013-04-21T18:39:14.547 回答