cURL Keep-alive如何运作?

时间:2015-03-26 13:41:04

标签: php curl nginx tcp keep-alive

我一直在努力解决这个问题,无法找到完全理解它的方法。

我有这段代码:

 <?php
function get2($url) {
  // Create a handle.
  $handle = curl_init($url);

  // Set options...

  // Do the request.
  $ret = curlExecWithMulti($handle);

  // Do stuff with the results...

  // Destroy the handle.
  curl_close($handle);

}

function curlExecWithMulti($handle) {
  // In real life this is a class variable.
  static $multi = NULL;

  // Create a multi if necessary.
  if (empty($multi)) {
    $multi = curl_multi_init();
  }

  // Add the handle to be processed.
  curl_multi_add_handle($multi, $handle);

  // Do all the processing.
  $active = NULL;
  do {
    $ret = curl_multi_exec($multi, $active);
  } while ($ret == CURLM_CALL_MULTI_PERFORM);

  while ($active && $ret == CURLM_OK) {
    if (curl_multi_select($multi) != -1) {
      do {
         $mrc = curl_multi_exec($multi, $active);
      } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
  }

  // Remove the handle from the multi processor.
  curl_multi_remove_handle($multi, $handle);

  return TRUE;
}

?>

上面的脚本是这样做的:我运行PHP并创建新的TCP连接,它返回数据然后关闭连接。

服务器正在使用HTTP 1.1和连接:keep-alive。

我想要的是,如果我运行脚本将创建连接,返回数据并且不关闭连接,当我再次运行PHP脚本时将使用相同的连接(当然,如果该连接在超时后没有到期)服务员。)

cURL可以吗?我了解multi错误中的cURL吗?

1 个答案:

答案 0 :(得分:1)

程序退出时,所有打开的套接字(实际上是所有打开的文件)都会关闭。无法重用从一个实例到另一个实例的连接(*)。您必须在应用程序中重新打开新连接或循环。

如果您想使用HTTP Keep-Alive,您的程序一定不能退出。

(*)有一些方法可以在一个进程中保持套接字打开,并通过Unix域套接字将其传递给其他进程,但这是我推荐的高级主题;我只是为了完整而提到它。

相关问题