【问题标题】:Curl - Sending hundreds of requests but only four at a time - ProgrammingCurl - 发送数百个请求,但一次只发送四个 - 编程
【发布时间】:2019-04-03 02:02:16
【问题描述】:

您如何着手解决这个问题?我有数百个请求要发送到 Curl,但我一次只能发送四个。

因此,我需要同时使用 curl 发出四个请求并处理它们的响应。但是,一旦有一个 curl 指针可用,我需要发送另一个请求。

这是因为,服务器一次只能处理四个请求,但我有数百个请求要发送到服务器。

以下是我从 curl 网站获得的代码

    int main(void)
    {
      const int HANDLECOUNT = 4;
      CURL *handles[HANDLECOUNT];
      CURLM *multi_handle;

      int still_running = 0; /* keep number of running handles */ 
      int i;

      CURLMsg *msg; /* for picking up messages with the transfer status */ 
      int msgs_left; /* how many messages are left */ 

      /* Allocate one CURL handle per transfer */ 
      for(i = 0; i<HANDLECOUNT; i++)
        handles[i] = curl_easy_init();

      /* set the options (I left out a few, you'll get the point anyway) */ 
      curl_easy_setopt(handles[0], CURLOPT_URL, "website");
      curl_easy_setopt(handles[0], CURLOPT_POSTFIELDS, XMLRequestToPost.c_str());
      curl_easy_setopt(handles[0], CURLOPT_POSTFIELDSIZE, (long)strlen(XMLRequestToPost.c_str())); 
      curl_easy_setopt(handles[1], CURLOPT_URL, "website");     
      curl_easy_setopt(handles[2], CURLOPT_URL, "website");    
      curl_easy_setopt(handles[3], CURLOPT_URL, "website");    

      /* set the request for other 3 handles too */
      /* init a multi stack */ 
      multi_handle = curl_multi_init();

      /* add the individual transfers */ 
      for(i = 0; i<HANDLECOUNT; i++)
        curl_multi_add_handle(multi_handle, handles[i]);

      /* we start some action by calling perform right away */ 
      curl_multi_perform(multi_handle, &still_running);

      while(still_running) {
      }


     }

【问题讨论】:

  • 你为什么不弄清楚什么已经完成并在那个槽中开始另一个传输? curl.haxx.se/libcurl/c/curl_multi_perform.html
  • 为什么一次只能发送4个? Curl 的多模式可以处理更多。
  • Shawn,这是接收请求的服务器的限制。我一次不能发送超过 4 个。
  • 你从curl_multi_perform()返回的still_running变量告诉你有多少正在进行,一旦它低于4你可以删除那个句柄,设置新选项并再次添加它以获得下一个转移进行中...
  • 谢谢丹尼尔。这太有趣了。将对其进行测试。

标签: c++ visual-studio curl visual-c++ libcurl


【解决方案1】:

创建一个线程安全队列来放入您的请求。

启动 4 个线程,每个线程都有自己的 CURL 对象。

让每个线程运行一个循环:

  • 从队列中拉下一个请求,
  • 发送它
  • 根据需要处理/发送响应,
  • 并重复

直到队列为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 2022-08-09
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多