35 lines
796 B
PHP
35 lines
796 B
PHP
|
<?php
|
||
|
|
||
|
namespace App\SSE;
|
||
|
|
||
|
/**
|
||
|
* Small class to abstract Server-Sent Events (SSE)
|
||
|
*
|
||
|
* https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
|
||
|
*/
|
||
|
class Sender
|
||
|
{
|
||
|
public function __construct()
|
||
|
{
|
||
|
header("Cache-Control: no-store");
|
||
|
header("Content-Type: text/event-stream");
|
||
|
|
||
|
// as session data is locked to prevent concurrent writes we
|
||
|
// make it read only to prevent the server from locking up
|
||
|
session_write_close();
|
||
|
}
|
||
|
|
||
|
public function send($data, $event = NULL): void
|
||
|
{
|
||
|
if ($event)
|
||
|
{
|
||
|
echo "event: $event\n";
|
||
|
}
|
||
|
echo "data: " . json_encode($data) ."";
|
||
|
echo "\n\n";
|
||
|
|
||
|
// send data to stream
|
||
|
ob_end_flush();
|
||
|
flush();
|
||
|
}
|
||
|
}
|