Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve documentation for closing response stream #452

Merged
merged 1 commit into from Apr 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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