【问题标题】:How does cURL Keep-alive works?cURL Keep-alive 是如何工作的?
【发布时间】:2015-05-30 13:25:21
【问题描述】:

我一直在研究这个,但找不到完全理解它的方法。

我有这个代码:

 <?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 可以吗?我是否理解 cURL 中的 multi 错误?

【问题讨论】:

    标签: php curl nginx tcp keep-alive


    【解决方案1】:

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

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

    (*) 有一些方法可以让一个进程内的套接字保持打开状态,并通过 Unix 域套接字将其传递给其他进程,但我建议不要这样做;我提到它只是为了完整性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-10
      • 2012-05-09
      • 2016-09-07
      • 1970-01-01
      • 2021-08-17
      • 2015-09-27
      • 2016-05-11
      • 2012-01-04
      相关资源
      最近更新 更多