【问题标题】:Boost socket not throwing EOF on disconnectionBoost socket在断开连接时不抛出EOF
【发布时间】:2014-01-28 07:29:29
【问题描述】:

我正在使用 Boost 库为我的一个 C++ 项目编写一个简单的下载服务。我想要的是在下载时如果我的连接中断,我应该停止下载。我读过不同的地方,当连接断开时套接字返回 EOF 错误,Boost 套接字也会这样做。但我的问题是,当连接断开时,boost socket 不会抛出 EOF,而是保持连接,一旦连接恢复,它会在停止的地方恢复下载。我不想恢复,我想退出,所以我会自己恢复。问题是当连接断开时为什么 boost socket 没有抛出 EOF 错误。以下是我的示例代码。我也尝试过异步实现,我也尝试过使用 socket.read_some 函数但行为相同。

std::string responseString = "";

try {
    // === Send HTTP Request to get Proxy End Point
    std::string apiPath = "/qtproject/archive/qt/4.0/" + filename;
    boost::asio::io_service io_service;

    // Get a list of endpoints corrosponding to the server name
    tcp::resolver resolver(io_service);
    tcp::resolver::query query(serverip, serverport);
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    // Try each endpoint untill we successfully establish a connection.
    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);

    boost::system::error_code error = boost::asio::error::host_not_found;
    boost::asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "GET " << apiPath << " HTTP/1.0\r\n";
    request_stream << "Host: " << serverip << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request
    boost::asio::write(socket, request);

    // === Read Server Response
    boost::asio::streambuf response;
    boost::asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);
    if (!response_stream || http_version.substr(0, 5) != "HTTP/") {
        std::cout << " Bad Server Response " << std::endl;
    }
    if (status_code != 200) {
        std::cout << "Bad Status Code = " << status_code << std::endl;
    }
    // Read the response headers, which are terminated by a blank line.
    //boost::asio::read_until(socket, response, "\r\n\r\n");
    //boost::system::error_code error; //boost::asio::buffer(data, sizeof data)
    unsigned char data[1024];
    socket.read_some(boost::asio::buffer(data, sizeof(data)), error);

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r");

    ofstream image;
    std::string filepath = "/home/farshad/TBD/" + filename;
    image.open(filepath.c_str());

    // Read until EOF, writing data to output as we go.
    int downloadedSize = 0;
    int readSize = 0;
    while ( (readSize = socket.read_some(boost::asio::buffer(data, sizeof(data)), error)) )
    {
            // When the connection is broken it keeps in this while loop, 
            // where I am expecting it to throw EOF error. Once connection is back, 
            // it resumes from the same while loop.
        downloadedSize += readSize;
        std::cout << "Data Read = " << downloadedSize <<  " Bytes\n";
        //memset(data, 0x0, sizeof(data));
        //image << &response;
        //std::cout << "Downloaded = " << (downloadedSize) << " Bytes\n";
    }

    //std::cout << "File Size = " << image.gcount() << std::endl;
    image.close();
    if (error != boost::asio::error::eof)
      throw boost::system::system_error(error);
    else if ( error == boost::asio::error::eof  ) {
        std::cout << "End of file approached";
        throw boost::system::system_error(error);
    }
}
catch ( std::exception& e)
{
    std::cout << "Exception: " << e.what() << std::endl;
}
catch ( ... )
{
    std::cout << "HURRAY: We got error" << std::endl;
}

更新 断线的性质是有人拔了网线,或者是ISP导致网络连接断开。

【问题讨论】:

  • 你不检查你是否真的一个错误,你会抛出一个system_error
  • 顺便说一句,如果您想与 C++ 中的 Web 服务器交谈,您可能需要查看 cpp-netlib。使用它会大大简化你的代码。
  • 我现在不能使用 cpp-netlib,因为这个 boost 代码在我的项目中太深了,现在我遇到了一个我正在研究它的错误。
  • this thread
  • 您所描述的“断开连接”并不是 TCP 套接字级别的断开连接。

标签: c++ sockets boost


【解决方案1】:

总结:按设计工作。 HTTP 在应用程序层面需要超时。

数据包超时时连接中断。在尝试传输之前,无法检测到电缆已断开的事实。如果网络断开但在下一次传输尝试之前再次连接,则连接不会中断,因为它适用于所有传输,没有理由认为它已中断。

当有传输并且网络断开时,连接可能需要几分钟才能断开,因为超时相当大,因为网络不承诺任何特定的性能。因此,如果您断开电缆,但在服务器超时之前再次连接,则传输将继续。因为故障是暂时的,而 TCP 旨在处理这些故障。必须这样做,因为即使一切正常,数据包偶尔也会丢失。

这仍然只适用于传输端。接收端不会检测到连接断开。当您断开网络并使其保持断开状态时,服务器可能会在几分钟后断定连接已断开。但是它不能告诉客户端并且客户端没有传输所以它找不到自己。因此,客户端将一直坐在那里等待数据永远。它不会再收到任何数据,因为服务器放弃了,但它不会发现,除非它尝试写入,但它不会。

因此您必须有计时器,如果您在一段时间内没有收到更多数据(通常超时时间为 5-10 分钟),您必须关闭连接并自己声明错误。每次接收到的块都应该重置计时器,因为传输可能需要比超时时间更长的时间。

请注意,以上所有内容都没有提到任何关于 boost 的内容。这些是 TCP/IP 的属性,并且对于它的任何接口和它的任何实现,行为都是相同的。另请注意,TCP/IP 有一个“keepalive”选项,它会导致系统(自动,无需您进一步干预)定期发送空数据包以检查连接是否断开,并且使用该选项您将在读取时收到 eof。但是,该选项不适用于 HTTP。它通常用于长时间保持连接并且可能长时间看不到流量的协议,例如 imap 或 ssh,但对于 HTTP,接收超时是首选解决方案。

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 2011-02-03
    • 2020-09-20
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    相关资源
    最近更新 更多