重用ASIO连接,read_some异常

时间:2013-04-18 20:56:29

标签: http boost network-programming boost-asio http-1.0

我目前正在尝试弄清楚如何正确重用asio套接字。我能够成功发出请求,并获得结果。第二次发出请求时,我得到一个异常:read_some:文件结束。第二次写似乎工作正常,我看到第二个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);
}

1 个答案:

答案 0 :(得分:3)

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

但是,在1.1版本中,连接是persistent by default,因此请求“HTTP / 1.1”应该可以解决此问题。