39 lines
886 B
PHP
39 lines
886 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 start(): void
|
|
{
|
|
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();
|
|
|
|
// we have to flush before because idk
|
|
ob_end_flush();
|
|
flush();
|
|
}
|
|
|
|
public function flush($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();
|
|
}
|
|
} |