Long Polling abre apenas a primeira coneção
Galera tenho um long Polling defeituoso.
ele funciona perfeitamente da primeira vez, apos disso não abre mais a conexão de 20 em 20 segundos como eu quero.
<?php
$timeStart = time();
$conn = new PDO('mysql:host=localhost;dbname=notificacoes', 'root', '');
if(isset($_POST['timestamp'])){
$timeStamp = $_POST['timestamp'];
}else{
$sql = "SELECT NOW() as now";
$sth = $conn->prepare($sql);
$sth->execute();
$row = $sth->fetchObject();
$timeStamp = $row->now;
echo $timeStamp;
}
$sql = "SELECT *FROM notific WHERE data > '$timeStamp'";
$sth1 = $conn->prepare($sql);
$newData = false;
$notific = array();
while (!$newData && (time() - $timeStart) < 20) {
$sth1->execute();
while($dados = $sth1->fetch(PDO::FETCH_ASSOC)){
$notific[] = $dados;
$newData = true;
}
usleep(500000);
}
$sql = "SELECT NOW() as now";
$sth = $conn->prepare($sql);
$sth->execute();
$row = $sth->fetchObject();
$timeStamp = $row->now;
$data = array('notificaoes'=>$notific, 'timestamp'=>$timeStamp);
echo json_encode($data);
JS
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function(){
pegaNotificacoes();
});
function pegaNotificacoes(timestamp){
var data = {};
if(typeof timestamp != 'undefined'){
data.timestamp = timestamp;
}
$.post('longPollin.php', data, function(res){
$('#resultados').append(res.notificacoes[0].nomeLoja+'-------'+res.timestamp+'<br/>');
pegaNotificacoes(res.timestamp);
}, 'json');
}
</script>
<div id="resultados"></div>
AJuda por favor.Discussão (0)
Carregando comentários...