I am trying to complete a connection using Long Polling, where the browser sends a request to the server and is waiting for a response. To prevent this port from being infinitely open, I created a routine so that every 10 seconds the server sends an empty response to the browser, stating that nothing has been done yet.
Everything working perfectly, I had no problem related to that.
My problem is that when the user clicks on a link on the page, the browser waits for the call to be able to refresh, that is, it can take up to 10 sec. This makes it look like the tool is slow.
Does anyone have any idea how to solve this?
Here is the JavaScript function used to make the call:
function loadJSON() {
if(libera) {
var data_file = http + "bibliotecas/longpolling/notificacoes.php";
var data = {};
data.n = long_n;
data.u = userchat;
data.m = msgchat;
data.c = chatUsuario;
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200) {
try {
var jsonObj = JSON.parse(http_request.responseText);
var qtd = jsonObj.funcao.length;
if(qtd > 0) {
var funcao = "";
for(var key in jsonObj.funcao) {
funcao = jsonObj.funcao[key];
MontarFuncao(eval(funcao),jsonObj.metodo[key]);
}
}
}
catch (e) {
//alert('Erro - '+ http_request.responseText);
}
loadJSON();
}
}
var string = JSON.stringify(data);
http_request.open("POST", data_file, true);
http_request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
http_request.setRequestHeader("Content-length", string.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(string);
return;
}
}
Here is the PHP function responsible for being left waiting for some change in the database:
ob_start();
$json = json_decode(file_get_contents('php://input'));
while($x < 5) {
if(time() >= (15 + $_SERVER['REQUEST_TIME']) || connection_aborted()) {
echo str_pad(NULL,1);
die(json_encode(array()));
flush();
ob_flush();
break;
}
//Funções de consulta ao BD (Se houver algo adiciona Array no variavel $retorno)
if(count($retorno) > 0) {
flush();
ob_flush();
echo json_encode($retorno);
exit;
}
else {
flush();
sleep(2);
$x++;
}
}