Skip to content

Commit

Permalink
Merge pull request #452 from clue-labs/close-streaming-response
Browse files Browse the repository at this point in the history
Improve documentation for closing response stream
  • Loading branch information
WyriHaximus committed Apr 15, 2022
2 parents b572e31 + a6bc13d commit 4862e84
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
10 changes: 9 additions & 1 deletion README.md
Expand Up @@ -1426,15 +1426,23 @@ may only support strings.
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
$stream = new ThroughStream();

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

Loop::addTimer(5, function() use ($timer, $stream) {
// end stream after a few seconds
$timeout = Loop::addTimer(5.0, function() use ($stream, $timer) {
Loop::cancelTimer($timer);
$stream->end();
});

// stop timer if stream is closed (such as when connection is closed)
$stream->on('close', function () use ($timer, $timeout) {
Loop::cancelTimer($timer);
Loop::cancelTimer($timeout);
});

return new React\Http\Message\Response(
React\Http\Message\Response::STATUS_OK,
array(
Expand Down
8 changes: 5 additions & 3 deletions examples/58-server-stream-response.php
Expand Up @@ -18,14 +18,16 @@
$stream->write(microtime(true) . PHP_EOL);
});

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

// stop timer if stream is closed (such as when connection is closed)
$stream->on('close', function () use ($timer) {
$stream->on('close', function () use ($timer, $timeout) {
Loop::cancelTimer($timer);
Loop::cancelTimer($timeout);
});

return new Response(
Expand Down

0 comments on commit 4862e84

Please sign in to comment.