php curl连接复用 keep-alive

2014-01-06 11:22  8718人阅读  评论 (0)
Tags: phpcurl

显示客户端的ip地址和端口

port.php

<?php
echo $_SERVER['REMOTE_ADDR'], ":", $_SERVER['REMOTE_PORT'], "\n";

file_get_contents测试代码

file_get_contents.php

<?php
$api_post_data = array(
        'username' => 'dotcoo',
        'password' => 'dotcoo',
);
$api_url = 'http://www.dotcoo.com/port.php';
$sock_context = array('http' => array(
        'method' => 'POST',
        'header' => "Content-Type: text/html; charset=utf-8", // \r\nConnection: close\r\n"; // 正式使用请添加,以免对方不主动断开连接.
        'content' => http_build_query($api_post_data),
));
$sock_context = stream_context_create($sock_context);
$response_json = file_get_contents($api_url, false, $sock_context);
echo $response_json;

$response_json = file_get_contents($api_url, false, $sock_context);
echo $response_json;

返回结果

127.0.0.1:51326
127.0.0.1:51327

file_get_contents每次都会打开新端口重新连接http服务器,不能复用同一个socket连接. 分析发现file_get_contents默认使用http/1.0,对方会主动断开连接,然后file_get_contents返回. 如果你设置了http版本为1.1对方检测到就不会主动断开连接,file_get_contents就会阻塞,虽然一个完成的http response已经传输完成,file_get_contents也不会返回,只有连接超时断开以后才会返回. 某些CDN服务器针对优化没有主动断开连接,也会出现此状况. 根据以上表象总结file_get_contents不能重复使用同一个socket连接,必须多次TCP/IP握手.仅供参考

curl测试代码

curl.php

$url = 'http://www.dotcoo.com/port.php';
$headers = array('Connection: keep-alive');
$data = array(
        'username' => 'dotcoo',
        'password' => 'dotcoo',
);

$ch = curl_init();
// curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

echo curl_exec($ch), "\n";

curl_setopt($ch, CURLOPT_URL, $url.'?time='.time());
echo curl_exec($ch), "\n";

curl_close($ch);

返回结果

127.0.0.1:54861
127.0.0.1:54861

根据结果可以看出curl使用了同一个socket连接,不必多次TCP/IP握手.

豫ICP备09035262号-1