1
См here для фона:Тонкий PHP и сервера Sent Events (SSE)
С Слим Как отправить несколько ответов на тот же запрос, не выходя из приложения?
См here для фона:Тонкий PHP и сервера Sent Events (SSE)
С Слим Как отправить несколько ответов на тот же запрос, не выходя из приложения?
Я использую Тонкий 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);
}
}
};
?>