Is there a way to keep a connection open between an Android app and a PHP script, so if there are any updates, the PHP script can push notifications out to the android app, rather than the app having to make a HTTP request every X minutes to ask for any updates?
I know this isn’t possible via Ajax without installing things on the server side to enable them, but I’m wondering if its any different on Android.
E.g if I did the following on the PHP side:
<?
set_time_limit(0);
while (true)
{
$updates = $updater->find();
if ($updates)
ob_flush( $updates->getAsJSON() );
sleep(60);
}
?>
Will something like this work to keep a connection open and push out updates to the android app?
The server is running Apache and PHP 5.
Your code will work in theory, but will also cause unneeded CPU usage, because you look for updates every minute, and, depending on
$updaterimplementation, this may waste CPU, memory and IO. If you want an event-driven communication not to waste resources, you need an event-based backend – and there are plenty of them out there, but none in PHP, and that’s because it’s a PHP limit. There’s no way, in a PHP script, to go multithread andwait(), so basically you can’t implement the Observer pattern, and this in turn prevents them from writing event-driven libraries in PHP.I don’t think you want to do this. Unless you can without any doubt count users on your fingers, this task cannot be handled by PHP. It’s not an issue with the webserver, it’s an issue with PHP itself. Each PHP request (either via
mod_php, fcgi,php-fpm) is handled with a new PHP process. This makes it impossible to scale, and that’s why you need to install use other server-side technologies to implement long polling.