仅在连接失败时使 libcURL 超时

make libcURL timeout only on connection failure

我在我的程序中使用了一些自动更新功能。如果连接失败,我希望程序继续尝试最多 15 秒,然后宣布失败。为了实现这一点,我使用以下 curl_easy_setopt 作为 cURL 简单选项:

curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15);

但是后来发现如果下载时间超过15秒就会提示超时错误

如何将 15 秒限制在失败的情况下?即,如果 15 秒没有连接?


更多信息

我使用的完整选项列表如下:

curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); //verify ssl peer
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); //verify ssl hostname
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, this); //pointer to the current class as it's a GUI program
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlProgress_CallbackFunc_UpdateProgress);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20);

开始调用是通过以下方式完成的:

CURLcode res = curl_easy_perform(curl);

如果您需要更多信息,请告诉我。

谢谢。

而不是

curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20);

使用

curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 15);

第一行是连接阶段的超时时间。建立连接后,超时变得无关紧要,但以下两行可确保如果 15 秒时间范围内的平均速度降至每秒 1 字节以下,则操作将中止。

同样值得注意的是,如果连接断开,curl 将不会尝试重新建立任何连接,因为如果物理连接(暂时)丢失,TCP 连接仍然可以保持,直到其中一方决定超时。