【问题标题】:keep-alive curl C htttps POSTkeep-alive curl C htttps POST
【发布时间】:2015-08-10 18:59:00
【问题描述】:

通过此代码,我使用 libcurl 将字符串发送到网络服务器并将数据写入 MySQL(在网络服务器上完成)。 我的问题是,对于这个函数的每次调用,程序都会开始与网络服务器进行新的密钥交换。我想与服务器建立持久连接。 我已经在这里和网上搜索过,但没有找到任何令人满意的解决方案。 多处理程序和强制保持活动仍然打开一个新连接。

以下是我建立 SSL 连接的代码:

CURL *curl;
CURLcode res;

res = curl_global_init(CURL_GLOBAL_DEFAULT);   // Check for errors 

if(res != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed: %s\n",
    curl_easy_strerror(res));
    return 1;
}

// curl handler 
curl = curl_easy_init();

if(curl) {
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, STRING);
    curl_easy_setopt(curl, CURLOPT_URL, "https://IP/something/something.php");
    curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //verbose output activated
    struct curl_slist *headers=NULL;
    headers = curl_slist_append(headers, "Content-Type: application/json");  // type JSON
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

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

    // Check for errors 
    if(res != CURLE_OK)
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

    // cleanup
    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
}
curl_global_cleanup();

【问题讨论】:

  • 感谢您使代码看起来很漂亮dragosht

标签: c curl https libcurl keep-alive


【解决方案1】:

由 Daniel Stenberg here 回答,这是一个类似/相同的问题。

在后续请求中重复使用相同的 curl 句柄!不要在它们之间再次调用 curl_easy_cleanup(curl) 和 curl_easy_init()。

所以解决方案是只调用一次 curl_easy_cleanup(curl) 和 curl_easy_init()。

【讨论】:

    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 2023-03-07
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    相关资源
    最近更新 更多