HTTP Keep-alive长连接libcurl设置接口
1. HTTP首部选项
Connection: Keep-alive
Keep-Alive: timeout=20
Keep-Alive选项用于限制保持多长时间。
但HTTP1.1规定了默认保持长连接,应该可以不再需要在HTTP首部携带这两个选项。
2.libcurl接口设置
curl_easy_setopt
#include <curl/curl.h>
CURLcode curl_easy_setopt(CURL *handle, CURLoption option, parameter);
NETWORK OPTIONS
必须要设置这三个网络选项
CURLOPT_TCP_KEEPALIVE
CURLOPT_TCP_KEEPIDLE
CURLOPT_TCP_KEEPINTVL
CURLOPT_TCP_KEEPALIVE
Pass a long. If set to 1, TCP keepalive probes will be sent. The delay and frequency of these probes can be controlled by the CURLOPT_TCP_KEEPIDLE and CURLOPT_TCP_KEEPINTVL options, provided the operating system supports them. Set to 0 (default behavior) to disable keepalive probes (Added in 7.25.0).
CURLOPT_TCP_KEEPIDLE
Pass a long. Sets the delay, in seconds, that the operating system will wait while the connection is idle before sending keepalive probes. Not all operating systems support this option. (Added in 7.25.0)
CURLOPT_TCP_KEEPINTVL
Pass a long. Sets the interval, in seconds, that the operating system will wait between sending keepalive probes. Not all operating systems support this option. (Added in 7.25.0)
CONNECTION OPTIONS
CURLOPT_TIMEOUT
Pass a long as parameter containing timeout - the maximum time in seconds that you allow the libcurl transfer operation to take. Normally, name lookups can take a considerable time and limiting operations to less than a few minutes risk aborting perfectly normal operations. This option may cause libcurl to use the SIGALRM signal to timeout system calls.
In unix-like systems, this might cause signals to be used unless CURLOPT_NOSIGNAL is set.
If both CURLOPT_TIMEOUT and CURLOPT_TIMEOUT_MS are set, the value set last will be used.
Since this puts a hard limit for how long time a request is allowed to take, it has limited use in dynamic use cases with varying transfer times. You are then advised to explore CURLOPT_LOW_SPEED_LIMIT, CURLOPT_LOW_SPEED_TIME or using CURLOPT_PROGRESSFUNCTION to implement your own timeout logic.
Default timeout is 0 (zero) which means it never times out during transfer.
EXAMPLE
CURL *curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
/* enable TCP keep-alive for this transfer */
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
/* keep-alive idle time to 120 seconds */
curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, 120L);
/* interval time between keep-alive probes: 60 seconds */
curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, 60L);
curl_easy_perform(curl);
}
CURLOPT_TIMEOUT 设置一定要大于CURLOPT_TCP_KEEPIDLE的设置,或者设置为默认值0(不超时), 否则可能你还没等到应答就已经超时了。
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 0);