Deka
Deka

Reputation: 1343

Is there another way to implements Long Polling in PHP

I have read some articles (like this, or this), and all of them give me the same way to implements Long Polling in PHP (using usleep() and loop), like that:

$source; // some data source - db, etc
$data = null; // our return data
$timeout = 30; // timeout in seconds
$now = time(); // start time

// loop for $timeout seconds from $now until we get $data
while((time() - $now) < $timeout) {
    // fetch $data
    $data = $source->getData();

    // if we got $data, break the loop
    if (!empty($data)) break;

    // wait 1 sec to check for new $data
    usleep(10000);
}

// if there is no $data, tell the client to re-request (arbitrary status message)
if (empty($data)) $data = array('status'=>'no-data');

// send $data response to client
echo json_encode($data);

Is there another way? I know that PHP is a script language only, but i would like a way that base on event rather than checking and doing or waiting until timeout. It maybe be something like Continuations in Java that would be perfect.

Upvotes: 1

Views: 130

Answers (2)

Cpu Nerd
Cpu Nerd

Reputation: 312

I would recommend: http://ape-project.org/

mature and scalable

Upvotes: 1

agusluc
agusluc

Reputation: 1465

You could try React: http://reactphp.org/

Is not very mature yet, but it may suit your needs. Instead of doing long pooling, you can do it async.

Upvotes: 1

Related Questions