PHP Comet. How to do it better?

I have a simple comet chat. JavaScript sends an ajax request with a long poll. When the server finds new messages in the database, it responds and gives JSON. Then, JavaScript will send the request again.

JavaScript:

function cometConnect(){ $.ajax({ cache:false, type:"get", data:'ts='+ts, url: urlBack, async: true, success: function (arr1) { //work with JSON //..... }, complete:function(){ cometConnect(true); nerr=false; }, dataType: "text" }); } 

Php

 $flag=true; $lastmodif = isset($_GET['ts']) ? $_GET['ts'] : 0; while($flag){ $q=mysql_query("SELECT text, posterId,modified, fromUserId,toUserId, login FROM commonMessage WHERE modified>$lastmodif"); while($r=mysql_fetch_row($q)){ $flag=false; //Prepare JSON... variable $resp //......... } usleep(5000); } echo $resp; 

The problem is this: this "while ($ flag)" can run for a long time (if no one is writing messages). Thus, Apache can throw exceptions (maximum runtime, sometimes 502 Bad Gateway or Gateway Timeout).

How to solve it?

use .htaccess and "php_value max_execution_time 0"?

or just send a new request from JavaScript when the server returns an error (does this make the messages slower)?

Maybe there is another way?

+4
source share
2 answers

if there are no messages to press from the server within 40 seconds, you send any response from the server, on the basic of which the client re-requests.

+4
source

You should check out the APE project. This is Ajax Push Engine, it can help in real time: www.ape-project.org

+6
source

Source: https://habr.com/ru/post/1340290/


All Articles