[英]How does cURL Keep-alive works?
I've been working on this and couldn't find a way to understand it fully. 我一直在努力,找不到完全理解它的方法。
I have this code: 我有以下代码:
<?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;
}
?>
The above script is doing this: I run the PHP and it creates new TCP connection, it returns data and then it closes the connection. 上面的脚本是这样做的:我运行PHP,它创建了新的TCP连接,它返回数据,然后关闭该连接。
The server is working on HTTP 1.1 and connection: keep-alive. 服务器正在使用HTTP 1.1和连接:keep-alive。
What i want is if i run the script will create connection, return data and NOT close the connection and when i run the PHP script again will use that same connection (of course if that connection didn't expire after the timeout of the sever). 我想要的是,如果我运行脚本将创建连接,返回数据并且不关闭连接,并且当我再次运行PHP脚本时将使用相同的连接(当然,如果该连接在服务器超时后没有过期) 。
Is that possible with cURL
? cURL
有可能吗? Am I understanding the multi
in cURL
wrong? 我是否理解cURL
的multi
错误?
When a program exits, all of its open sockets (indeed, all open files) are closed. 程序退出时,将关闭所有打开的套接字(实际上是所有打开的文件)。 There is no way to reuse a connection from one instance to another(*). 无法重用从一个实例到另一个实例的连接(*)。 You must re-open a new connection or loop within your application. 您必须在应用程序中重新打开一个新的连接或循环。
If you want to use HTTP Keep-Alive, your program must not exit. 如果要使用HTTP Keep-Alive,则程序不得退出。
(*) There are ways to keep a socket open inside one process and pass it to others via Unix domain sockets but that is an advanced topic I recommend against; (*)有多种方法可以使一个套接字在一个进程内保持打开状态,并通过Unix域套接字将其传递给其他进程,但这是我建议的高级主题; I mention it only for completeness. 我仅出于完整性而提及它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.