2014-09-28 63 views
1

下面是PHP一个典型的多卷曲请求例如:PHP多卷曲请求,做一些工作同时等待该响应

$mh = curl_multi_init(); 

foreach ($urls as $index => $url) { 
    $curly[$index] = curl_init($url); 
    curl_setopt($curly[$index], CURLOPT_RETURNTRANSFER, 1); 
    curl_multi_add_handle($mh, $curly[$index]); 
} 

// execute the handles 
$running = null; 
do { 
    curl_multi_exec($mh, $running); 
    curl_multi_select($mh); 
} while($running > 0); 

// get content and remove handles 
$result = array(); 
foreach($curly as $index => $c) { 
    $result[$index] = curl_multi_getcontent($c); 
    curl_multi_remove_handle($mh, $c); 
} 

// all done 
curl_multi_close($this->mh); 

该方法包括3个步骤: 1.准备数据 2.发送请求和等待他们完成 3.收集回复

我想将步骤#2分成2部分,首先发送所有请求,然后收集所有的响应,并做一些有用的工作,而不是等待,例如,处理最后一组请求的响应。

所以,我怎么可以拆分这部分代码

$running = null; 
do { 
    curl_multi_exec($mh, $running); 
    curl_multi_select($mh); 
} while($running > 0); 

成独立的部分?

  1. 发送所有的请求
  2. 做一些别的工作,同时等待
  3. 检索所有的答复

我想是这样的:

// Send the requests 
$running = null; 
curl_multi_exec($mh, $running); 

// Do some job while waiting 
// ... 

// Get all the responses 
do { 
    curl_multi_exec($mh, $running); 
    curl_multi_select($mh); 
} while($running > 0); 

,但它似乎没有正常工作。

+0

你能多描述一下“看起来不能正常工作吗?” – wavemode 2014-09-28 20:09:30

+0

即使将睡眠(10)放在它之前,第二个周期中的应答也没有准备好(做... ...)。你可以自己运行代码,看看它不能按预期工作。 – 2014-09-29 06:42:11

回答

0

我找到了解决办法,这里是如何启动的所有请求,而无需等待响应

do { 
    curl_multi_exec($mh, $running); 
} while (curl_multi_select($mh) === -1); 

那么我们可以做任何其他的工作,后来赶上响应的任何时间。