繁体   English   中英

如果没有互联网连接,则持续加载

[英]continuously loading if there is no internet connection

我目前正在开发一个在线控制的房屋,但是互联网连接检查器存在问题。

我有这段代码来检测是否有互联网连接或没有互联网连接。

$check = @fsockopen("www.google.com", 80); 
if($check){
    return true;
    fclose($check);
}else{
     return false;
     fclose($check);
}

但是问题是,当我的Raspberry Pi没有互联网连接时,它将永远持续加载页面。

完整的脚本在这里

<?php
    function checkConnection(){
        $check = @fsockopen("www.google.com", 80); 
        if($check){
            return true;
            fclose($check);
        }else{
             return false;
             fclose($check);
        }
    }
    if(checkConnection()==true){
        echo '[{"status":"success","result":"Internet Connection is Available"}]';
    }else{
        echo '[{"status":"fail","result":"No Internet Connection"}]';
    }
?>

功能上的微小变化也许可以启发这种情况。 例如:

   function checkConnection() {
         $fp = @fsockopen("www.google.com", 80, $errno, $errstr, 3); 
         if (!$fp) {
             return "$errstr ($errno)<br />\n";
         } else {
             return true;
         }
    }
    $con = checkConnection();
    if ($con===true) {
        echo json_encode( ["status" => "success","result" => "Internet Connection is Available"] );
    } else {
        //  should not be - No Internet Connection is Available
        echo json_encode( ["status" => "fail","result" => $con] );
    }

PS:在PHPFiddle中尝试一下,并确保将端口从80更改为83 当然,这并不意味着您没有Internet连接,但是您在指定端口到达的主机不会回复。 无论如何,它只会使函数失败并返回错误消息。 另外,请务必注意fsocopen中3秒的timeout限制,因为您可以根据需要进行更改。

编辑

一种更简单,也许更准确的方法可以解决您的问题。

   function checkConnection($hostname) {           
         $fp = gethostbyname($hostname);
         if (!inet_pton($fp)) {
            return json_encode( ["status" => "fail","result" => "Internet Connection is not Available or Host {$hostname} is wrong or does not exist."] ); 
         } else {
            return json_encode( ["status" => "success","result" => "Internet Connection is Available. Host {$hostname} exists and resolves to {$fp}"] );
         }
    }
    echo checkConnection('www.google.com');

您可能想在php.net中检查此注释,以设置gethostbyname替代选项。

fsockopen将超时作为最后一个参数,仅在连接套接字时适用

DNS查找也可能是一个因素,AFAIK不能控制它的超时,除非在这种情况下如果要使用gethostbyname()可以使用

putenv('RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1');

将DNS查找限制为1s

根据您的代码,这就是我将如何实现它。

function is_connected()
{
    //1. provide a timeout to your socket
    //2. use example.com as a domain, that's what it's made for (testing)
    $socket = @fsockopen("www.example.com", 80, $err_no, $err_str, 5);
    if ($socket){
        fclose($socket);
        return true; 
    }
    return false;
}

$success = json_encode(["status" => "success","result" => "Internet is Available"]);
$failure = json_encode(["status" => "fail","result" => "Internet is Unavailable"]);

echo is_connected() ? $success : $failure;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM