Home  >  Article  >  Backend Development  >  PHP fsockopen函数问题,本脚本无阻塞触发其他脚本失败

PHP fsockopen函数问题,本脚本无阻塞触发其他脚本失败

WBOY
WBOYOriginal
2016-06-06 20:15:33753browse

    $host = 'www.abc.com';
    $port = 80;
    $query = "admin/mi.php?key=value";
    
    $fp = @fsockopen($host, $port, $errno, $errstr, 30);
    if ($fp) {
        $out = "GET /".$query." HTTP/1.1\r\n";
        $out .= "Host: ".$host."\r\n";
        $out .= "Connection: Close\r\n\r\n";
        // 0,资源流将会被转换为非阻塞模式;1,资源流将会被转换为阻塞模式。
        @stream_set_blocking($fp, 0);
        @stream_set_timeout($fp, 5);
        fwrite($fp, $out);
        // sleep(1); //关键地方
        fclose($fp);
    } else {
        echo "$errstr ($errno)
\n"; } ------------- 看关键地方 有SLEEP(1) 请求 www.abc.com 成功,没有 SLEEP(1)请求不成功,FSOCKOPEN运作机制是什么呢? 我想在这个脚本里无阻塞访问www.abc.com/admin/mi.php 不需要返回数据。只是需要触发MI.PHP执行。

回复内容:

    $host = 'www.abc.com';
    $port = 80;
    $query = "admin/mi.php?key=value";
    
    $fp = @fsockopen($host, $port, $errno, $errstr, 30);
    if ($fp) {
        $out = "GET /".$query." HTTP/1.1\r\n";
        $out .= "Host: ".$host."\r\n";
        $out .= "Connection: Close\r\n\r\n";
        // 0,资源流将会被转换为非阻塞模式;1,资源流将会被转换为阻塞模式。
        @stream_set_blocking($fp, 0);
        @stream_set_timeout($fp, 5);
        fwrite($fp, $out);
        // sleep(1); //关键地方
        fclose($fp);
    } else {
        echo "$errstr ($errno)
\n"; } ------------- 看关键地方 有SLEEP(1) 请求 www.abc.com 成功,没有 SLEEP(1)请求不成功,FSOCKOPEN运作机制是什么呢? 我想在这个脚本里无阻塞访问www.abc.com/admin/mi.php 不需要返回数据。只是需要触发MI.PHP执行。

关键地方加上 usleep(1000); 【延时1000微秒 = 1毫秒 = 0.001秒】 就可以了。目前稳定。

--- 云网开

$fp被你close了。无阻塞不代表能保证数据发完,发送数据过程其实是挺漫长的,要域名解析,要建立链接,还没等事情做完,你就close了,不成功的概率很高。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn