用戶端與伺服器端是通過HTTP協議進行串連通訊,用戶端發起請求,伺服器端接收到請求後執行處理,並返回處理結果。
有時伺服器需要執行很耗時的操作,這個操作的結果並不需要返回給用戶端。但因為php是同步執行的,所以用戶端需要等待服務處理完才可以進行下一步。
test-a.php
<?phpheader("Content-type:text/html;charset=utf-8");$url = 'http://localhost/test/testb.php';echo 'starttime:'.microtime().'<br />';$param = array( 'time'=>time()); doAsyncRequest($url, $param); echo 'endtime'.microtime();function doAsyncRequest($url, $param=array()){ $urlinfo = parse_url($url); $host = $urlinfo['host']; $path = $urlinfo['path']; $query = isset($param)? http_build_query($param) : ''; $port = 80; $errno = 0; $errstr = ''; $timeout = 10; $fp = fsockopen($host, $port, $errno, $errstr, $timeout); $out = "POST ".$path." HTTP/1.1\r\n"; $out .= "host:".$host."\r\n"; $out .= "content-length:".strlen($query)."\r\n"; $out .= "content-type:application/x-www-form-urlencoded\r\n"; $out .= "connection:close\r\n\r\n"; $out .= $query; fputs($fp, $out); fclose($fp); }?>testb.php
<?phpheader("Content-type:text/html;charset=utf-8");sleep(15);//等待15秒file_put_contents('filename.txt', $_POST);print_r($_POST);exit;?>