php - Slim PHP 和服务器发送事件 (SSE)

标签 php slim server-sent-events

参见here背景:

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

最佳答案

我正在使用 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);
        }
    }
};
?>

关于php - Slim PHP 和服务器发送事件 (SSE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34690326/

相关文章:

javascript - 如何在悬停时更改模式弹出窗口的字体大小

python - 手动将 tf.contrib.slim 升级到 tf 2.0

javascript - SSE (EventSource) 在 1 小时 22 分钟后超时。有什么方法可以保持它的持久性吗?

java - HTML5 服务器端事件 (SSE)

Golang 服务器发送事件 - 服务器发送事件处理程序是否不断调用自身?

php - 在php中连接两个整数

php - 为 Admin Sonata 添加自己的字段

php - 计算 MySQL 数据库的 Unicode 字符数

php - 间歇性 PHP 抽象类错误

php - 超薄自动加载器和命名空间问题