@@ -1105,6 +1105,50 @@ installed in your application::
1105
1105
1106
1106
``CachingHttpClient `` accepts a third argument to set the options of the ``HttpCache ``.
1107
1107
1108
+ Consuming Server-Sent Events
1109
+ ----------------------------
1110
+
1111
+ This component provides an `EventSource `_ implementation to consume Server-Sent Events.
1112
+ Use the :class: `Symfony\\ Component\\ HttpClient\\ EventSourceHttpClient `, open a
1113
+ connection to a server with the `text/event-stream ` content type and consume the stream::
1114
+
1115
+ use Symfony\Component\HttpClient\EventSourceHttpClient;
1116
+
1117
+ $client = new EventSourceHttpClient($client, 10);
1118
+ $source = $client->connect('GET', 'http://localhost:8080/events');
1119
+ while ($source) {
1120
+ foreach ($client->stream($source, 2) as $r => $chunk) {
1121
+ // You should handle these chunks yourself
1122
+ if ($chunk->isTimeout()) {
1123
+ dump([
1124
+ 'timeout' => [
1125
+ 'retry' => 1 + count($r->getInfo('previous_info') ?? [])
1126
+ ],
1127
+ ]);
1128
+ continue;
1129
+ }
1130
+ if ($chunk->isLast()) {
1131
+ dump([
1132
+ 'eof' => [
1133
+ 'retries' => count($r->getInfo('previous_info') ?? [])
1134
+ ],
1135
+ ]);
1136
+ $source = null;
1137
+ return;
1138
+ }
1139
+
1140
+ // This is a special ServerSentEvent chunk holding the pushed message
1141
+ dump($chunk);
1142
+ }
1143
+ }
1144
+
1145
+ The default reconnection time is `10 ` seconds and is given onto the second argument of
1146
+ the :class: `Symfony\\ Component\\ HttpClient\\ EventSourceHttpClient `. The method
1147
+ :method: `Symfony\\ Component\\ HttpClient\\ Response\\ AsyncResponse::stream ` takes an
1148
+ optional timeout argument.
1149
+ The :class: `Symfony\\ Component\\ HttpClient\\ Chunk\\ ServerSentEvent ` is a special chunk
1150
+ capable of parsing an event stream as specified by the `EventSource `_ specification.
1151
+
1108
1152
Interoperability
1109
1153
----------------
1110
1154
@@ -1380,3 +1424,4 @@ However, using ``MockResponse`` allows simulating chunked responses and timeouts
1380
1424
.. _`Symfony Contracts` : https://github.com/symfony/contracts
1381
1425
.. _`libcurl` : https://curl.haxx.se/libcurl/
1382
1426
.. _`amphp/http-client` : https://packagist.org/packages/amphp/http-client
1427
+ .. _`EventSource` : https://www.w3.org/TR/eventsource/#eventsource
0 commit comments