参见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/