Antoine Bluchet
Contributed by Antoine Bluchet in #36692

Server-sent events is an Internet standard used to push data to web pages. Its JavaScript API is built around an EventSource object, which listens to the events sent from some URL. The events are a stream of data (served with the text/event-stream MIME type) with the following format:

1
2
3
4
5
6
data: This is the first message.

data: This is the second message, it
data: has two lines.

data: This is the third message.

Symfony's HttpClient component provides a solid foundation to consume stream responses. That's why in Symfony 5.2. we've introduced a new feature to consume Server-sent events using Symfony HttpClient.

This feature is built around a new EventSourceHttpClient class which wraps your normal HTTP client and streams the server-sent events as stream chunks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use Symfony\Component\HttpClient\Chunk\ServerSentEvent;
use Symfony\Component\HttpClient\EventSourceHttpClient;
use Symfony\Component\HttpClient\HttpClient;

$client = HttpClient::create();
$client = new EventSourceHttpClient($client);
// this is the URL that sends server events
$source = $client->connect('https://localhost:8080/events');

while ($source) {
    foreach ($client->stream($source, 2) as $r => $chunk) {
        if ($chunk->isTimeout()) {
            // do something ...
            continue;
        }
        if ($chunk->isLast()) {
            // do something ...
            return;
        }

        // this is a special ServerSentEvent chunk holding the pushed message
        if ($chunk instanceof ServerSentEvent) {
            // do something with the message
        }
    }
}
Published in #Living on the edge