curl单链接异步下载多个文件

xingyun86 2019-4-11 1652

curl

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <unistd.h>
#endif
#include <curl/multi.h>
  
static const char *urls[] = {
  "http://www.microsoft.com",
  "http://www.opensource.org",
  "http://www.google.com",
  "http://www.yahoo.com",
  "http://www.ibm.com",
  "http://www.mysql.com",
  "http://www.oracle.com",
  "http://www.ripe.net",
  "http://www.iana.org",
  "http://www.amazon.com",
  "http://www.netcraft.com",
  "http://www.heise.de",
  "http://www.chip.de",
  "http://www.ca.com",
  "http://www.cnet.com",
  "http://www.news.com",
  "http://www.cnn.com",
  "http://www.wikipedia.org",
  "http://www.dell.com",
  "http://www.hp.com",
  "http://www.cert.org",
  "http://www.mit.edu",
  "http://www.nist.gov"
};
  
#define MAX 10 
#define CNT sizeof(urls)/sizeof(char*) 
  
static size_t cb(char *d, size_t n, size_t l, void *p)
{
  /* take care of the data here, ignored in this example */
  (void)d;
  (void)p;
  return n*l;
}
 int nIndex=0;
static void init(CURLM *cm, int i)
{
  CURL *eh = curl_easy_init();
  
  curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, cb);//所有的下载均调用了这个回调函数
  curl_easy_setopt(eh, CURLOPT_HEADER, 0L);       //输出内容时不含消息头
  curl_easy_setopt(eh, CURLOPT_URL, urls[i]);     //请求的网址
  curl_easy_setopt(eh, CURLOPT_PRIVATE, urls[i]);  //在这把调用的网址存下,后面curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &url);查询出来
  curl_easy_setopt(eh, CURLOPT_VERBOSE, 0L);       //如果你想CURL报告每一件意外的事情,设置这个选项为一个非零值
  curl_easy_setopt(eh, CURLOPT_WRITEDATA, (void *)&nIndex);    //设置调用cb函数时传递cb函数的第四个参数
  curl_easy_setopt(eh, CURLOPT_USERAGENT, "Lavf/55.13.102");  //设置useragent
  curl_multi_add_handle(cm, eh);
}
  
int main(void)
{
  CURLM *cm;
  CURLMsg *msg;
  long L;
  unsigned int C=0;
  int M, Q, U = -1;
  fd_set R, W, E;
  struct timeval T;
  
  curl_global_init(CURL_GLOBAL_ALL);
  
  cm = curl_multi_init();
  
  /* we can optionally limit the total amount of connections this multi handle
     uses */
  curl_multi_setopt(cm, CURLMOPT_MAXCONNECTS, (long)MAX);
  
  for(C = 0; C < MAX; ++C) {
    init(cm, C);
  }
  
  while(U) {
    curl_multi_perform(cm, &U);  //执行并发请求,非阻塞,立即返回
  
    if(U) {
      FD_ZERO(&R);
      FD_ZERO(&W);
      FD_ZERO(&E);
      //获取cm需要监听的文件描述符集合,如果返回的M等于-1,需要等一会然后再次调用curl_multi_perform,等多久?建议至少100毫秒,但你可能想在你自己的特定条件下测试它,找到一个合适的值
      if(curl_multi_fdset(cm, &R, &W, &E, &M)) {
        fprintf(stderr, "E: curl_multi_fdset\n");
        return EXIT_FAILURE;
      }
  
      if(curl_multi_timeout(cm, &L)) {
        fprintf(stderr, "E: curl_multi_timeout\n");
        return EXIT_FAILURE;
      }
      if(L == -1)
        L = 100;
  
      if(M == -1) {
#ifdef WIN32
        Sleep(L);
#else
        sleep((unsigned int)L / 1000);
#endif
      }
      else {
        T.tv_sec = L/1000;
        T.tv_usec = (L%1000)*1000;
        /*确定一个或多个套接口的状态,可查询它的可读性、可写性及错误状态信息。
          返回值:
         select()调用返回处于就绪状态并且已经包含在fd_set结构中的描述字总数;如果超时则返回0;否则的话,返回SOCKET_ERROR(-1)错误,应用程序可通过WSAGetLastError()获取相应错误代码。
       */
        if(0 > select(M+1, &R, &W, &E, &T)) {
              fprintf(stderr, "E: select(%i,,,,%li): %i: %s\n",M+1, L, errno, strerror(errno));
              return EXIT_FAILURE;
        }
      }
    }
/*获取当前解析的cURL的相关传输信息
查询批处理句柄是否单独的传输线程中有消息或信息返回。消息可能包含诸如从单独的传输线程返回的错误码或者只是传输线程有没有完成之类的报告。
重复调用这个函数,它每次都会返回一个新的结果,直到这时没有更多信息返回时,FALSE 被当作一个信号返回。通过msgs_in_queue返回的整数指出将会包含当这次函数被调用后,还剩余的消息数。
Warning
返回的资源指向的数据调用curl_multi_remove_handle()后将不会存在。
 
*/
 
    while((msg = curl_multi_info_read(cm, &Q))) {
      if(msg->msg == CURLMSG_DONE) {
        char *url;
        CURL *e = msg->easy_handle;
        curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &url);
        fprintf(stderr, "R: %d - %s <%s>\n",
                msg->data.result, curl_easy_strerror(msg->data.result), url);
        curl_multi_remove_handle(cm, e);
        curl_easy_cleanup(e);
      }
      else {
        fprintf(stderr, "E: CURLMsg (%d)\n", msg->msg);
      }
      if(C < CNT) {
        init(cm, C++);
        U++; /* just to prevent it from remaining at 0 if there are more
                URLs to get */
      }
    }
  }
  
  curl_multi_cleanup(cm);
  curl_global_cleanup();
  
  return EXIT_SUCCESS;
}
/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at https://curl.haxx.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ***************************************************************************/ /* <DESC>
 * Multiplexed HTTP/2 downloads over a single connection
 * </DESC>
 */ #include <stdio.h>#include <stdlib.h>#include <string.h> /* somewhat unix-specific */ #include <sys/time.h>#include <unistd.h> /* curl stuff */ #include <curl/curl.h> 
#ifndef CURLPIPE_MULTIPLEX/* This little trick will just make sure that we don't enable pipelining for
   libcurls old enough to not have this symbol. It is _not_ defined to zero in
   a recent libcurl header. */ #define CURLPIPE_MULTIPLEX 0
#endif struct transfer {
  CURL *easy;  unsigned int num;
  FILE *out;
};
 
#define NUM_HANDLES 1000
 staticvoid dump(const char *text, int num, unsigned char *ptr, size_t size,          char nohex)
{
  size_t i;
  size_t c;
   unsigned int width = 0x10;
   if(nohex)    /* without the hex output, we can fit more on screen */ 
    width = 0x40;
 
  fprintf(stderr, "%d %s, %lu bytes (0x%lx)\n",
          num, text, (unsigned long)size, (unsigned long)size);
   for(i = 0; i<size; i += width) {
 
    fprintf(stderr, "%4.4lx: ", (unsigned long)i);
     if(!nohex) {      /* hex not disabled, show it */ 
      for(c = 0; c < width; c++)        if(i + c < size)
          fprintf(stderr, "%02x ", ptr[i + c]);        else
          fputs("   ", stderr);
    }
     for(c = 0; (c < width) && (i + c < size); c++) {      /* check for 0D0A; if found, skip past and start a new line of output */ 
      if(nohex && (i + c + 1 < size) && ptr[i + c] == 0x0D &&
         ptr[i + c + 1] == 0x0A) {
        i += (c + 2 - width);        break;
      }
      fprintf(stderr, "%c",
              (ptr[i + c] >= 0x20) && (ptr[i + c]<0x80)?ptr[i + c]:'.');      /* check again for 0D0A, to avoid an extra \n if it's at width */ 
      if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D &&
         ptr[i + c + 2] == 0x0A) {
        i += (c + 3 - width);        break;
      }
    }
    fputc('\n', stderr); /* newline */ 
  }
}
 staticint my_trace(CURL *handle, curl_infotype type,             char *data, size_t size,             void *userp)
{  const char *text;  struct transfer *t = (struct transfer *)userp;  unsigned int num = t->num;
  (void)handle; /* prevent compiler warning */    switch(type) {  case CURLINFO_TEXT:
    fprintf(stderr, "== %d Info: %s", num, data);    /* FALLTHROUGH */ 
  default: /* in case a new one is introduced to shock us */ 
    return 0;
   case CURLINFO_HEADER_OUT:
    text = "=> Send header";    break;  case CURLINFO_DATA_OUT:
    text = "=> Send data";    break;  case CURLINFO_SSL_DATA_OUT:
    text = "=> Send SSL data";    break;  case CURLINFO_HEADER_IN:
    text = "<= Recv header";    break;  case CURLINFO_DATA_IN:
    text = "<= Recv data";    break;  case CURLINFO_SSL_DATA_IN:
    text = "<= Recv SSL data";    break;
  }
 
  dump(text, num, (unsigned char *)data, size, 1);  return 0;
}
 static void setup(struct transfer *t, int num)
{  char filename[128];
  CURL *hnd;
 
  hnd = t->easy = curl_easy_init();
 
  snprintf(filename, 128, "dl-%d", num);
 
  t->out = fopen(filename, "wb");
   /* write to this file */ 
  curl_easy_setopt(hnd, CURLOPT_WRITEDATA, t->out);
   /* set the same URL */ 
  curl_easy_setopt(hnd, CURLOPT_URL, "https://localhost:8443/index.html");
   /* please be verbose */ 
  curl_easy_setopt(hnd, CURLOPT_VERBOSE, 1L);  curl_easy_setopt(hnd, CURLOPT_DEBUGFUNCTION, my_trace);  curl_easy_setopt(hnd, CURLOPT_DEBUGDATA, t);
   /* HTTP/2 please */ 
  curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
   /* we use a self-signed test server, skip verification during debugging */ 
  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, 0L);  curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYHOST, 0L);
 
#if (CURLPIPE_MULTIPLEX > 0)  /* wait for pipe connection to confirm */ 
  curl_easy_setopt(hnd, CURLOPT_PIPEWAIT, 1L);
#endif}
 /*
 * Download many transfers over HTTP/2, using the same connection!
 */ int main(int argc, char **argv)
{  struct transfer trans[NUM_HANDLES];
  CURLM *multi_handle;  int i;  int still_running = 0; /* keep number of running handles */ 
  int num_transfers;  if(argc > 1) {    /* if given a number, do that many transfers */ 
    num_transfers = atoi(argv[1]);    if((num_transfers < 1) || (num_transfers > NUM_HANDLES))
      num_transfers = 3; /* a suitable low default */ 
  }  else
    num_transfers = 3; /* suitable default */    /* init a multi stack */ 
  multi_handle = curl_multi_init();
   for(i = 0; i < num_transfers; i++) {
    setup(&trans[i], i);
     /* add the individual transfer */ 
    curl_multi_add_handle(multi_handle, trans[i].easy);
  }
   curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
   /* we start some action by calling perform right away */ 
  curl_multi_perform(multi_handle, &still_running);
   while(still_running) {    struct timeval timeout;    int rc; /* select() return code */ 
    CURLMcode mc; /* curl_multi_fdset() return code */  
    fd_set fdread;
    fd_set fdwrite;
    fd_set fdexcep;    int maxfd = -1;
     long curl_timeo = -1;
 
    FD_ZERO(&fdread);
    FD_ZERO(&fdwrite);
    FD_ZERO(&fdexcep);
     /* set a suitable timeout to play around with */ 
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;
     curl_multi_timeout(multi_handle, &curl_timeo);    if(curl_timeo >= 0) {
      timeout.tv_sec = curl_timeo / 1000;      if(timeout.tv_sec > 1)
        timeout.tv_sec = 1;      else
        timeout.tv_usec = (curl_timeo % 1000) * 1000;
    }
     /* get file descriptors from the transfers */ 
    mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
     if(mc != CURLM_OK) {
      fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc);      break;
    }
     /* On success the value of maxfd is guaranteed to be >= -1. We call
       select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
       no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
       to sleep 100ms, which is the minimum suggested value in the       curl_multi_fdset() doc. */      if(maxfd == -1) {
#ifdef _WIN32
      Sleep(100);
      rc = 0;
#else
      /* Portable sleep for platforms other than Windows. */ 
      struct timeval wait = { 0, 100 * 1000 }; /* 100ms */ 
      rc = select(0, NULL, NULL, NULL, &wait);
#endif
    }    else {      /* Note that on some platforms 'timeout' may be modified by select().
         If you need access to the original value save a copy beforehand. */ 
      rc = select(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
    }
     switch(rc) {    case -1:      /* select error */ 
      break;    case 0:    default:      /* timeout or readable/writable sockets */ 
      curl_multi_perform(multi_handle, &still_running);      break;
    }
  }
   for(i = 0; i < num_transfers; i++) {    curl_multi_remove_handle(multi_handle, trans[i].easy);    curl_easy_cleanup(trans[i].easy);
  }
   curl_multi_cleanup(multi_handle);
   return 0;
}


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回