Skip to content

Commit 3e23981

Browse files
committed
Document EventSourceHttpClient
1 parent 52c2ca0 commit 3e23981

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

http_client.rst

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1105,6 +1105,50 @@ installed in your application::
11051105

11061106
``CachingHttpClient`` accepts a third argument to set the options of the ``HttpCache``.
11071107

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+
11081152
Interoperability
11091153
----------------
11101154

@@ -1380,3 +1424,4 @@ However, using ``MockResponse`` allows simulating chunked responses and timeouts
13801424
.. _`Symfony Contracts`: https://github.com/symfony/contracts
13811425
.. _`libcurl`: https://curl.haxx.se/libcurl/
13821426
.. _`amphp/http-client`: https://packagist.org/packages/amphp/http-client
1427+
.. _ `EventSource`: https://www.w3.org/TR/eventsource/#eventsource

0 commit comments

Comments
 (0)