为什么我的服务器在Ajax中使用长拉时会冻结


Why my server freezes when using long pull with Ajax?

当我在jQuery上使用Ajax进行查询时,我尝试使用长拉的方法,但我的服务器关闭或没有响应,我的网站变得太慢,就像在stanby中一样,或者冻结了,我该怎么办?

我的PHP;

session_start();
$chat=new chat;
$class=new tools;
$idenvia=isset($_GET['idenvia'])? $_GET['idenvia']: '';
$idreceptor=isset($_GET['idreceptor'])? $_GET['idreceptor']: '';
$cantidad= isset($_GET['cantidad'])? $_GET['cantidad']: '';
$control=$_GET['control'];
//$ultima_modif=isset($_SESSION['fecha'])?$_SESSION['fecha']:0;
if($control==1){
echo json_encode($chat->leer_chat($idreceptor,$idenvia,$control,$cantidad,NULL));
}
if($control==2){
$dir='log/log_'.$_SESSION['id'].'.txt';
$ultima_modif=filemtime($dir);  
$modifica_actual=isset($_GET['tiempo'])? $_GET['tiempo']: 0;//0
set_time_limit(0);
while($ultima_modif<=$modifica_actual){
    clearstatcache();
    $ultima_modif=filemtime($dir);
    sleep(1);

    //echo '{"0":{"activo":2}}';    
    //flush();
}
           $res=$chat->leer_chat($_SESSION['id'],NULL,$control,$ultima_modif);  
        echo json_encode($res); 
        //unlink($dir);
        flush();    

    }

这是我的JQUERY代码,在这里我用AJAX 获取我的php的响应

 function leer_chat_interval(){
    $.ajax({
        url:enlace,
        type:'GET',
        async:true,
        data:{'control': 2,'tiempo':tiempo},
        success:function(dato){
            eval('var json='+dato);
                if(json[0].activo==1){
                    //if(json.length!=0){   
                        leer_chat(json[0].idenvia,json[0].idrecibe,1,json[0].nombre,json[0].mifoto,1,1);
                        $('#msg_chat'+json[0].idrecibe).attr('name',"{'recibe':'"+json[0].idenvia+"','envia':'"+json[0].idrecibe+"','foto':'"+json[0].mifoto+"'}");
                        setTimeout(function(){
                            $('#header_chat'+json[0].idenvia).css('background-color','#09C')
                            setTimeout(function(){
                                $('#header_chat'+json[0].idenvia).css('background-color','#F90')
                            },1000)
                        },1000);
                        tiempo=json[0].tiempo;
                        noerror=true;
                    }else{noerror=false;}
                },
        datatype:"json",        
        complete:function(dato){
                if(!noerror){
                setTimeout(function(){
                    leer_chat_interval()
                    },5000)
                }else{
                    leer_chat_interval();
                    noerror=false;
                    }
            },
            timeout:30000
        }); 
}

您的问题是:

while(1)

您不应该让脚本无限循环来处理ajax"长轮询";相反,每个ajax调用都会运行一个有限的请求,收集结果,然后重复。在您的示例中,每次激发ajax请求时,都会启动一个新的无限运行脚本;服务器自然会在积累了几个之后崩溃。