PHP实现异步请求非阻塞

PHP实现异步请求非阻塞

 

function fosck_post($url, $param){

    $host = parse_url($url, PHP_URL_HOST);
    $port = 80;

    $urlInfo = parse_url($url);
    if (isset($urlInfo['scheme']) && strcasecmp($urlInfo['scheme'], 'https') === 0) //HTTPS
    {
        $prefix = 'ssl://';
        $port = 443;
    }else{  //HTTP
        $prefix = 'tcp://';
        $port = isset($urlInfo['port']) ? $urlInfo['port'] : 80;
    }


    $errno = '';
    $errstr = '';
    $timeout = 30;

    $data = http_build_query($param);

    // create connect
    $fp = fsockopen($prefix. $host, $port, $errno, $errstr, $timeout);

    if(!$fp){
        return false;
    }

    // send request
    $out = "POST ${url} HTTP/1.1\r\n";
    $out .= "Host:${host}\r\n";
    $out .= "Content-type:application/x-www-form-urlencoded\r\n";
    $out .= "Content-length:".strlen($data)."\r\n";
    $out .= "Connection:close\r\n\r\n";
    $out .= "${data}";

    fwrite($fp, $out);

    //忽略执行结果;否则等待返回结果
    //        if(APP_DEBUG === true){
    if(false){
        $ret = '';
        while (!feof($fp)) {
            $ret .= fgets($fp, 128);
        }
    }

    usleep(20000); //fwrite之后马上执行fclose,nginx会直接返回499

    fclose($fp);
}

 

posted @ 2021-08-16 17:36  MargoHu  阅读(178)  评论(0编辑  收藏  举报