libcurl的使用--如何复用连接

来源:互联网 发布:足彩n串1算法 编辑:程序博客网 时间:2024/06/15 15:37

正常使用curl的流程是:

curl_global_init

curl_easy_init

。。。调用数据

curl_easy_cleanup

curl_global_cleanup


这样去写逻辑,每次都会建立tcp连接,浪费了网络时间


如果是多线程变成,应该这样,去重用http连接:


1、main函数里面【主线程】:

curl_global_init【这个函数只能在主线程调用1次】

pthread_key_create

。。。创建线程

等待线程

curl_global_cleanup


2、线程里面:

  CURL* p1= curl_easy_init();
  pthread_setspecific(g_curl_key, (void *)p1);


 当然,如果要在主线程使用url函数,也需要这2个函数。

3、url访问函数:【多线程调用】

        curl = (CURL *)pthread_getspecific(g_curl_key);
        curl_easy_setopt(curl, CURLOPT_URL, url);
        /* 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);

        /* Now specify the POST data */
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, params);

        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &tmp);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_string);

        /* Perform the request, res will get the return code */
        curl_easy_perform(curl);


0 0