My connection using Server-Sent Events (and Javascript / PHP) continues to decline immediately

Yesterday, I plunged into Server-Sent events, as they were a great way to create news for the online game I am creating. I had a working script that could subscribe to my channel, and a script that could pull the news feed from the MySql database in a few minutes, but for some reason it disconnects the connection every time ... (and every 3 seconds rebuilds, which makes it no better than just using AJAX at specific time intervals, for example)

Used javascript:

var source = new EventSource('http://theobg.itselementary.site50.net/gamefeed.php'); source.onmessage = function(e) { $("#gamefeed").html(e.data); } 

PHP I use:

 <?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); header('Connection: keep-alive'); function sendMsg($id, $msg) { echo "id: $id" . PHP_EOL; echo "data: $msg" . PHP_EOL; echo PHP_EOL; ob_flush(); flush(); } //The file for connecting to my database here... $gameid = 1; $serverTime = time(); //Some mysql query to get the gamefeed from the database here..., gamefeed is structured like this: NEWS&OTHERNEWS&OLDERNEWS&EVENOLDERNEWS sendMsg($serverTime, $gamefeed); ?> 

I watched all over the Internet, but everything seems to work fine with me, except that the connection is not "kept alive" and I have no idea why this ... can anyone help me?

Thanks in advance, Dalionzo

+4
source share
1 answer

You need to check the data and send it using a loop.

 <?php while(true){ //check for updates here if($updates){ sendMsg($id,$data); } sleep(1);//loosen it up } 

Also, to simplify the coding, you can try my php library for events sent by the server. Here

+2
source

All Articles