Skip to content

Commit 4862e84

Browse files
authored
Merge pull request #452 from clue-labs/close-streaming-response
Improve documentation for closing response stream
2 parents b572e31 + a6bc13d commit 4862e84

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

README.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1426,15 +1426,23 @@ may only support strings.
14261426
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
14271427
$stream = new ThroughStream();
14281428

1429+
// send some data every once in a while with periodic timer
14291430
$timer = Loop::addPeriodicTimer(0.5, function () use ($stream) {
14301431
$stream->write(microtime(true) . PHP_EOL);
14311432
});
14321433

1433-
Loop::addTimer(5, function() use ($timer, $stream) {
1434+
// end stream after a few seconds
1435+
$timeout = Loop::addTimer(5.0, function() use ($stream, $timer) {
14341436
Loop::cancelTimer($timer);
14351437
$stream->end();
14361438
});
14371439

1440+
// stop timer if stream is closed (such as when connection is closed)
1441+
$stream->on('close', function () use ($timer, $timeout) {
1442+
Loop::cancelTimer($timer);
1443+
Loop::cancelTimer($timeout);
1444+
});
1445+
14381446
return new React\Http\Message\Response(
14391447
React\Http\Message\Response::STATUS_OK,
14401448
array(

examples/58-server-stream-response.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,16 @@
1818
$stream->write(microtime(true) . PHP_EOL);
1919
});
2020

21-
// demo for ending stream after a few seconds
22-
Loop::addTimer(5.0, function() use ($stream) {
21+
// end stream after a few seconds
22+
$timeout = Loop::addTimer(5.0, function() use ($stream, $timer) {
23+
Loop::cancelTimer($timer);
2324
$stream->end();
2425
});
2526

2627
// stop timer if stream is closed (such as when connection is closed)
27-
$stream->on('close', function () use ($timer) {
28+
$stream->on('close', function () use ($timer, $timeout) {
2829
Loop::cancelTimer($timer);
30+
Loop::cancelTimer($timeout);
2931
});
3032

3133
return new Response(

0 commit comments

Comments
 (0)