超薄的PHP和服务器发送事件(SSE)

时间:2016-01-09 06:10:14

标签: php slim server-sent-events

有关背景信息,请参阅here

使用Slim,如何在不退出应用程序的情况下向同一请求发送多个响应?

1 个答案:

答案 0 :(得分:1)

我正在使用Slim Api版本2,我通过这种方式将服务器发送的事件添加到现有的api中:

在index.php中:

$app = new \Slim\Slim();

// other code
....

// this is the route I want to use for the event stream
$app->get( '/psoback/eventstream',
           function() use ($app)
           {
                require_once('event.php');
                $app->eventstream = new ServerSentEventHandler(); 
           }
         );

// here goes the rest of my api definitions
...

$app->run();

if(isset($app->eventstream))
{
   $app->eventstream->Run();
}

event.php看起来像这样: (例如https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

<?php
class ServerSentEventHandler
{
    function __construct()
    {

    }

    function Run()
    {
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        $counter = rand(1, 10);
        while (1) 
        {
          // Every second, sent a "ping" event.

          echo "event: ping\n";
          $curDate = date(DATE_ISO8601);
          echo 'data: {"time": "' . $curDate . '"}';
          echo "\n\n";

          // Send a simple message at random intervals.

          $counter--;

          if (!$counter) 
          {
            echo 'data: This is a message at time ' . $curDate . "\n\n";
            $counter = rand(1, 10);
          }

          ob_end_flush();
          flush();
          sleep(1);
        }
    }
};
?>