@@ -1143,6 +1143,52 @@ installed in your application::
11431143
11441144``CachingHttpClient `` accepts a third argument to set the options of the ``HttpCache ``.
11451145
1146+ Consuming Server-Sent Events
1147+ ----------------------------
1148+
1149+ This component provides an `EventSource `_ implementation to consume Server-Sent Events.
1150+ Use the :class: `Symfony\\ Component\\ HttpClient\\ EventSourceHttpClient `, open a
1151+ connection to a server with the `text/event-stream ` content type and consume the stream::
1152+
1153+ use Symfony\Component\HttpClient\EventSourceHttpClient;
1154+
1155+ $client = new EventSourceHttpClient($client, 10);
1156+ $source = $client->connect('http://localhost:8080/events');
1157+ while ($source) {
1158+ foreach ($client->stream($source, 2) as $r => $chunk) {
1159+ // You should handle these chunks yourself
1160+ if ($chunk->isTimeout()) {
1161+ dump([
1162+ 'timeout' => [
1163+ 'retry' => 1 + count($r->getInfo('previous_info') ?? [])
1164+ ],
1165+ ]);
1166+ continue;
1167+ }
1168+ if ($chunk->isLast()) {
1169+ dump([
1170+ 'eof' => [
1171+ 'retries' => count($r->getInfo('previous_info') ?? [])
1172+ ],
1173+ ]);
1174+ $source = null;
1175+ return;
1176+ }
1177+
1178+ // This is a special ServerSentEvent chunk holding the pushed message
1179+ if ($chunk instanceof ServerSentEvent) {
1180+ dump($chunk);
1181+ }
1182+ }
1183+ }
1184+
1185+ The default reconnection time is `10 ` seconds and is given onto the second argument of
1186+ the :class: `Symfony\\ Component\\ HttpClient\\ EventSourceHttpClient `. The method
1187+ :method: `Symfony\\ Component\\ HttpClient\\ Response\\ AsyncResponse::stream ` takes an
1188+ optional timeout argument.
1189+ The :class: `Symfony\\ Component\\ HttpClient\\ Chunk\\ ServerSentEvent ` is a special chunk
1190+ capable of parsing an event stream as specified by the `EventSource `_ specification.
1191+
11461192Interoperability
11471193----------------
11481194
@@ -1419,3 +1465,4 @@ However, using ``MockResponse`` allows simulating chunked responses and timeouts
14191465.. _`libcurl` : https://curl.haxx.se/libcurl/
14201466.. _`amphp/http-client` : https://packagist.org/packages/amphp/http-client
14211467.. _`cURL options` : https://www.php.net/manual/en/function.curl-setopt.php
1468+ .. _`EventSource` : https://www.w3.org/TR/eventsource/#eventsource
0 commit comments