---
title: "curl_writer"
author: "byytj"
date: "2013-01-05T00:25:28Z"
tags: []
categories: ["编程语言"]
slug: "curl-writer"
draft: false
lastmod: "2013-01-05T00:25:28Z"
id: 1759945
url: "https://byytj.iteye.com/blog/1759945"
---

#include &lt;string&gt;  
#include &lt;iostream&gt;

#include &lt;curl/curl.h&gt;  
#include &lt;sys/time.h&gt;  
#include &lt;unistd.h&gt;

using namespace std;

size\_t curl\_writer(void \*buffer, size\_t size, size\_t count, void * stream)  
{  
    std::string * pStream = static\_cast&lt;std::string \*&gt;(stream);  
    (\*pStream).append((char \*)buffer, size * count);

    return size * count;  
};

/\**  
 * 生成一个easy curl对象，进行一些简单的设置操作  
 \*/  
CURL * curl\_easy\_handler(const std::string & sUrl,  
                         const std::string & sProxy,  
                         std::string & sRsp,  
                         unsigned int uiTimeout)  
{  
    CURL * curl = curl\_easy\_init();

    curl\_easy\_setopt(curl, CURLOPT\_URL, sUrl.c\_str());  
    curl\_easy\_setopt(curl, CURLOPT\_NOSIGNAL, 1);

    if (uiTimeout &gt; 0)  
    {  
        curl\_easy\_setopt(curl, CURLOPT\_TIMEOUT\_MS, uiTimeout);  
    }  
    if (!sProxy.empty())  
    {  
        curl\_easy\_setopt(curl, CURLOPT\_PROXY, sProxy.c\_str());  
    }

    // write function //  
    curl\_easy\_setopt(curl, CURLOPT\_WRITEFUNCTION, curl\_writer);  
    curl\_easy\_setopt(curl, CURLOPT\_WRITEDATA, &sRsp);

    return curl;  
}

/\**  
 * 使用select函数监听multi curl文件描述符的状态  
 * 监听成功返回0，监听失败返回-1  
 \*/  
int curl\_multi\_select(CURLM * curl\_m)  
{  
    int ret = 0;

    struct timeval timeout\_tv;  
    fd\_set  fd\_read;  
    fd\_set  fd\_write;  
    fd\_set  fd\_except;  
    int     max\_fd = -1;

    // 注意这里一定要清空fdset,curl\_multi\_fdset不会执行fdset的清空操作  //  
    FD\_ZERO(&fd\_read);  
    FD\_ZERO(&fd\_write);  
    FD\_ZERO(&fd\_except);

    // 设置select超时时间  //  
    timeout\_tv.tv\_sec = 1;  
    timeout\_tv.tv\_usec = 0;

    // 获取multi curl需要监听的文件描述符集合 fd\_set //  
    curl\_multi\_fdset(curl\_m, &fd\_read, &fd\_write, &fd\_except, &max\_fd);

    /\**  
     * When max\_fd returns with -1,  
     * you need to wait a while and then proceed and call curl\_multi\_perform anyway.  
     * How long to wait? I would suggest 100 milliseconds at least,  
     * but you may want to test it out in your own particular conditions to find a suitable value.  
     \*/  
    if (-1 == max\_fd)  
    {  
        return -1;  
    }

    /\**  
     * 执行监听，当文件描述符状态发生改变的时候返回  
     * 返回0，程序调用curl\_multi\_perform通知curl执行相应操作  
     * 返回-1，表示select错误  
     * 注意：即使select超时也需要返回0，具体可以去官网看文档说明  
     \*/  
    int ret\_code = ::select(max\_fd + 1, &fd\_read, &fd\_write, &fd\_except, &timeout\_tv);  
    switch(ret\_code)  
    {  
    case -1:  
        /* select error \*/  
        ret = -1;  
        break;  
    case 0:  
        /* select timeout \*/  
    default:  
        /* one or more of curl's file descriptors say there's data to read or write\*/  
        ret = 0;  
        break;  
    }

    return ret;  
}

#define MULTI\_CURL\_NUM 3

// 这里设置你需要访问的url //  
std::string     URL     = "[http://website.com](http://website.com)";  
// 这里设置代理ip和端口  //  
std::string     PROXY   = "ip:port";  
// 这里设置超时时间  //  
unsigned int    TIMEOUT = 2000; /* ms \*/

/\**  
 * multi curl使用demo  
 \*/  
int curl\_multi\_demo(int num)  
{  
    // 初始化一个multi curl 对象 //  
    CURLM * curl\_m = curl\_multi\_init();

    std::string     RspArray\[num];  
    CURL *          CurlArray\[num];

    // 设置easy curl对象并添加到multi curl对象中  //  
    for (int idx = 0; idx &lt; num; ++idx)  
    {  
        CurlArray\[idx] = NULL;  
        CurlArray\[idx] = curl\_easy\_handler(URL, PROXY, RspArray\[idx], TIMEOUT);  
        if (CurlArray\[idx] == NULL)  
        {  
            return -1;  
        }  
        curl\_multi\_add\_handle(curl\_m, CurlArray\[idx]);  
    }

    /*  
     * 调用curl\_multi\_perform函数执行curl请求  
     * url\_multi\_perform返回CURLM\_CALL\_MULTI\_PERFORM时，表示需要继续调用该函数直到返回值不是CURLM\_CALL\_MULTI\_PERFORM为止  
     * running\_handles变量返回正在处理的easy curl数量，running\_handles为0表示当前没有正在执行的curl请求  
     \*/  
    int running\_handles;  
    while (CURLM\_CALL\_MULTI\_PERFORM == curl\_multi\_perform(curl\_m, &running\_handles))  
    {  
        cout &lt;&lt; running\_handles &lt;&lt; endl;  
    }

    /\**  
     * 为了避免循环调用curl\_multi\_perform产生的cpu持续占用的问题，采用select来监听文件描述符  
     \*/  
    while (running\_handles)  
    {  
        if (-1 == curl\_multi\_select(curl\_m))  
        {  
            cerr &lt;&lt; "select error" &lt;&lt; endl;  
            break;  
        } else {  
            // select监听到事件，调用curl\_multi\_perform通知curl执行相应的操作 //  
            while (CURLM\_CALL\_MULTI\_PERFORM == curl\_multi\_perform(curl\_m, &running\_handles))  
            {  
                cout &lt;&lt; "select: " &lt;&lt; running\_handles &lt;&lt; endl;  
            }  
        }  
        cout &lt;&lt; "select: " &lt;&lt; running\_handles &lt;&lt; endl;  
    }

    // 输出执行结果 //  
    int         msgs\_left;  
    CURLMsg *   msg;  
    while((msg = curl\_multi\_info\_read(curl\_m, &msgs\_left)))  
    {  
        if (CURLMSG\_DONE == msg-&gt;msg)  
        {  
            int idx;  
            for (idx = 0; idx &lt; num; ++idx)  
            {  
                if (msg-&gt;easy\_handle == CurlArray\[idx]) break;  
            }

            if (idx == num)  
            {  
                cerr &lt;&lt; "curl not found" &lt;&lt; endl;  
            } else  
            {  
                cout &lt;&lt; "curl \[" &lt;&lt; idx &lt;&lt; "] completed with status: "  
                        &lt;&lt; msg-&gt;data.result &lt;&lt; endl;  
                cout &lt;&lt; "rsp: " &lt;&lt; RspArray\[idx] &lt;&lt; endl;  
            }  
        }  
    }

    // 这里要注意cleanup的顺序 //  
    for (int idx = 0; idx &lt; num; ++idx)  
    {  
        curl\_multi\_remove\_handle(curl\_m, CurlArray\[idx]);  
    }

    for (int idx = 0; idx &lt; num; ++idx)  
    {  
        curl\_easy\_cleanup(CurlArray\[idx]);  
    }

    curl\_multi\_cleanup(curl\_m);

    return 0;  
}

/\**  
 * easy curl使用demo  
 \*/  
int curl\_easy\_demo(int num)  
{  
    std::string     RspArray\[num];

    for (int idx = 0; idx &lt; num; ++idx)  
    {  
        CURL * curl = curl\_easy\_handler(URL, PROXY, RspArray\[idx], TIMEOUT);  
        CURLcode code = curl\_easy\_perform(curl);  
        cout &lt;&lt; "curl \[" &lt;&lt; idx &lt;&lt; "] completed with status: "  
                &lt;&lt; code &lt;&lt; endl;  
        cout &lt;&lt; "rsp: " &lt;&lt; RspArray\[idx] &lt;&lt; endl;

        // clear handle //  
        curl\_easy\_cleanup(curl);  
    }

    return 0;  
}

#define USE\_MULTI\_CURL

struct timeval begin\_tv, end\_tv;

int main(int argc, char * argv\[])  
{  
    if (argc &lt; 2)  
    {  
        return -1;  
    }  
    int num = atoi(argv\[1]);

    // 获取开始时间 //  
    gettimeofday(&begin\_tv, NULL);  
#ifdef USE\_MULTI\_CURL  
    // 使用multi接口进行访问 //  
    curl\_multi\_demo(num);  
#else  
    // 使用easy接口进行访问 //  
    curl\_easy\_demo(num);  
#endif  
    // 获取结束时间  //  
    struct timeval end\_tv;  
    gettimeofday(&end\_tv, NULL);

    // 计算执行延时并输出，用于比较  //  
    int eclapsed = (end\_tv.tv\_sec - begin\_tv.tv\_sec) * 1000 +  
                   (end\_tv.tv\_usec - begin\_tv.tv\_usec) / 1000;

    cout &lt;&lt; "eclapsed time:" &lt;&lt; eclapsed &lt;&lt; "ms" &lt;&lt; endl;

    return 0;  
}