我一直在做这件事,但找不到一种完全理解它的方法。
我有这样的代码:
<?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和connection: keep-alive。
我想要的是,如果我运行,脚本将创建连接,返回数据,并且不关闭连接,当我再次运行PHP脚本时,将使用相同的连接(当然,如果该连接在服务器超时后没有过期)。
使用cURL可以做到这一点吗?我对cURL中的multi的理解是错误的吗?
发布于 2015-03-26 23:45:52
当程序退出时,它的所有打开的套接字(实际上是所有打开的文件)都会关闭。无法重用从一个实例到另一个实例的连接(*)。您必须在应用程序中重新打开新的连接或循环。
如果你想使用HTTP Keep-Alive,你的程序一定不能退出。
(*)有一些方法可以在一个进程内保持套接字打开,并通过Unix域套接字将其传递给其他进程,但这是一个我建议不要使用的高级主题;我提到它只是为了完整性。
https://stackoverflow.com/questions/29279983
复制相似问题