保持活动 curl C https POST

keep-alive curl C htttps POST

使用此代码,我使用 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();

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

Re-use the same curl handle in subsequent requests! Don't call curl_easy_cleanup(curl) and curl_easy_init() again between them.

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