Method
ServerSentEvents::send
Send one event.
Description#
public ServerSentEvents::send(
string $data,
?string $event = null,
?string $id = null,
?int $retry = null
): void$data may hold any line endings: each line becomes a data: field, which the browser
joins with "\n" again. Line breaks (and NUL in $id) are removed from $event and $id,
so they cannot inject a field.
Parameters#
- $data string
- The event's data
- $event ?string = null
- The event's name: the browser's
addEventListener($event, ...),messagewhen null - $id ?string = null
- Sets the browser's last event id, which it sends back as
Last-Event-IDwhen it reconnects - $retry ?int = null
- Milliseconds the browser waits before it reconnects
Errors / Exceptions#
| Exception | When |
|---|---|
IOException | When the client is gone |
Examples#
use Swerve\ClientRequest;
use Swerve\RequestHandler;
use Swerve\ServerSentEvents;
$app = new RequestHandler(function (ClientRequest $request) {
$events = new ServerSentEvents($request);
$events->send('plain message'); // EventSource's onmessage
$events->send("two\nlines", event: 'note'); // addEventListener('note', ...)
$events->send('{"price":101.5}', event: 'tick', id: '42', retry: 5000);
});
if (debug_backtrace()) {
return $app; // swerve loads this file: it is the application's swerve.php
}
// Run directly: serve the application with swerve, and send it requests
require __DIR__ . '/../serve.php';
serve(__FILE__, ["GET /events HTTP/1.1\r\nHost: example\r\n\r\n"]);Output
HTTP/1.1 200 OK
content-type: text/event-stream
cache-control: no-cache
x-accel-buffering: no
Server: Swerve
Transfer-Encoding: chunked
Connection: close
15
data: plain message
23
event: note
data: two
data: lines
36
event: tick
id: 42
retry: 5000
data: {"price":101.5}
0$sse->send(json_encode($order), event: 'order', id: (string) $order->id);