5
I am trying to complete a connection using Long Polling, where the browser sends a request to the server and awaits a response. To avoid this door being open endlessly, I created a routine so that every 10 seconds the server sends an empty answer to the browser, stating that there was nothing so far.
Everything is working perfectly, I had no problem related to that.
My problem is that when the user clicks on some link on the page, the browser waits for the answer of the call to be able to update, that is, it can take up to 10 seconds. This makes it look like the tool is slow.
Does anyone have any idea how to fix this?
Follow 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;
}
}
Follow the PHP function responsible for staying open waiting for some changes 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++;
}
}
Is it possible to show partial information? or all the necessary information comes only once? I imagine you have one
.png
or.gif
or message that something is happening on background. If not, it is important for the user to know that the page is handling the request.– Sergio
You can show us your ajax call?
– tinos
When vc opened the connection with the server using xmlhttp.open, vc uses Async TRUE or FALSE?
– Peter
You could use Signalr with ASP.Net
– Tony
I added the code used to facilitate. Thanks for all your help so far.
– Rodrigo Coelho