I want to send regular updates from server to client. For that I used server-sent event. I\'m pasting the codes below:
Client side
SSE is an interesting technology, but one that comes with a choking side effect on implementations using APACHE/PHP backend.
When I first found out about SSE I got so excited that I replaced all Ajax polling code with SSE implementation. Only a few minutes of doing this I notice my CPU usage went up to 99/100 and the fear that my server was soon going to be brought down, forced me to revert the changes back to the friendly old Ajax polling. I love PHP and even though I knew SSE would work better on Node.is, I just wasn't ready to go that route yet!
After a period of critical thinking, I came up with an SSE APACHE/PHP implementation that could work without literally choking my server to death.
I'm going to share my SSE server side code with you, hopefully it helps someone overcome the challenges of implementing SSE with PHP.
$data));
echo "id: $last_postid \n"; // this is the lastEventID
echo "data: $data\n\n"; // our data
/* flush to avoid waiting for script to terminate - make
sure its in the same order */
@ob_flush(); flush();
}
// the amount of time that has been spent on this script
$time_stayed = intval(floor($time_to_stay) - time());
/* if we have stayed more than time to stay, then abort
this connection to free up CPU resource */
if ( $time_stayed <= 0 ) { exit; }
/* we simply wait 5 seconds and continue again from
start . We don't want to keep pounding our DB since we
are in a tight loop so we sleep a few seconds and start
from top*/
sleep(5);
}