php 異步非阻塞調用

fsockopen()

$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);

if (!$fp) {
    die('error fsockopen');
}

// 轉換到非阻塞模式
stream_set_blocking($fp, 0);

$http = "GET /save.php  / HTTP/1.1\r\n";
$http .= "Host: www.example.com\r\n";
$http .= "Connection: Close\r\n\r\n";

fwrite($fp, $http);
fclose($fp);
$fp = fsockopen($host,$port,$error_code,$error_msg,1);
    if(!$fp) {
        return array('error_code' => $error_code,'error_msg' => $error_msg);
    }
    else {
        stream_set_blocking($fp,true);//開啓了手冊上說的非阻塞模式
        stream_set_timeout($fp,1);//設置超時
        $header = "GET $path HTTP/1.1\r\n";
        $header.="Host: $host\r\n";
        $header.="Connection: close\r\n\r\n";//長連接關閉
        fwrite($fp, $header);
        usleep(1000); // 這一句也是關鍵,如果沒有這延時,可能在nginx服務器上就無法執行成功
        fclose($fp);
        return array('error_code' => 0);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章