javascript - SSE loads lots of data and paralyzes AJAX post requests -


this sse_server.php file

include_once 'server_files/init2.php'; //this file includes connection file database , functions  header('content-type: text/event-stream'); header('cache-control: no-cache');  $assocarray = array();  $fetch_article = $dbh->prepare("select                                          article_author_id,                                          article_author_un,                                         article_id,                                          article_cover,                                         article_title,                                         article_desc                                     articles order article_id desc"); $fetch_article->execute();  while ($fetch = $fetch_article->fetch(pdo::fetch_assoc))  {     $article_author_id    = $fetch['article_author_id'];     $article_author_u     = $fetch['article_author_un'];     $article_id           = $fetch['article_id'];      $article_cover        = $fetch['article_cover'];     $article_title        = $fetch['article_title'];     $article_desc         = $fetch['article_desc'];       $randomnum = rand(0,500);      //insert random number along article's info | random number value , contents key                 $assocarray[                             'randomnum'.'|'.                    //0                             $article_author_id.'|'.             //1                             $article_author_u.'|'.              //2                             $article_id.'|'.                    //3                             $article_cover.'|'.                 //4                             $article_title.'|'.                 //5                             $article_desc                       //6                              ]  = $randomnum; }  //sort array arsort($assocarray, 1);  //echo '<pre>'; //print_r($assocarray);  //while(true){      $var = '';     foreach ($assocarray $key => $value) {          $var .=  $value .' => ' . $key . '`|||`<br>';     }     echo "retry: 6000\n";     echo "data: {$var}\n\n";     ob_flush();     flush();  //} 

and how i'm processing data in client.php file

    <div id="feeds"></div>     <script>          if(typeof(eventsource)!=="undefined") {              var esource = new eventsource("sse_server.php");               //detect message received             esource.addeventlistener('message', function(event) {               var jsv_feeds = event.data;             var eventlist = document.getelementbyid("feeds");               var jsv_feedsarray = jsv_feeds.split('`|||`');  //seperator                eventlist.innerhtml = jsf_tofetch(jsv_feedsarray);               }, false);         }         else {             document.getelementbyid("feeds").innerhtml="whoops! browser doesn't receive server-sent events.";         }           function jsf_tofetch(jsp_array)          {             var string = ''; //an empty string              (var = 0; < jsp_array.length-1; i++)              {                  jsv_feed = jsp_array[i].split('|');                  jsv_randomnum           = jsv_feed[0];                 jsv_article_author_id   = jsv_feed[1];                 jsv_article_author_u    = jsv_feed[2];                 jsv_article_id          = jsv_feed[3];                 jsv_article_cover       = jsv_feed[4];                 jsv_article_title       = jsv_feed[5];                 jsv_article_desc        = jsv_feed[6];                   string += jsv_randomnum +'<li><b>'+jsv_article_author_u+'</b><!--process rest in similar way--> </li>';               } // loop ends here             return '<ol>' + string + '</ol>';         }      </script> 

the problem if use foreach loop only, reconnects every 6 seconds.
, if wrap foreach inside while loop keeps connection alive continously keeps on sending data. loads lot of data within seconds. makes ajax post request slow executed via page simultaneously.

why happening ?
how can keep connection open, not send data, , not slow down ajax post requests.

ps: have visited these links -
http://www.html5rocks.com/en/tutorials/eventsource/basics/
php event source keeps executing

may didn't understood them enough. if boiled down simpler terms, kindly it!

thanks in advance!

you want using while(true){} loop you've commented out in sse_server.php. sse script should never exit (until socket closed, happen client-side, i.e. javascript script closing it, or browser window being closed).

the reason have problems when using while loop there no sleep() or wait action inside while loop. sending data client (the same data on , on again!), @ maximum rate.

conceptually, i'm guessing after code:

$lastid = 0; while(true){   $fetch_article = $dbh->prepare("select somewhere conditions , articleid > ?");   $results = $fetch_article->execute($lastid);   if(has 1+ results) {      foreach($results){         echo result formatted sse         $lastid = ...;      }      flush();ob_flush();   }   sleep(5); } 

this saying poll db every 5 seconds new records. if there no new records nothing - goes sleep 5 seconds. if there new records pushes them out on sse client.

you can adjust 5 second sleep find balance between cpu usage on server , latency. shorter sleep means lower latency (your clients new data sooner), higher cpu on server.

aside: lastid approach above way of detecting records have seen, , have not yet seen. if have unique id in table, auto_increment. but, alternatively, if db records inserted created timestamp, query becomes:

$now = 0; while(true){     $stmt = prepare( "select ... , created > ?" );     $stmt->execute( $now );     $now = time();     ...process results ...     sleep(5); } 

(slightly safer set $now maximum created timestamp found in results, rather time() each time; otherwise possible record slip through cracks , not sent clients.)


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -