forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path58-server-stream-response.php
44 lines (34 loc) · 1.23 KB
/
58-server-stream-response.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
use Psr\Http\Message\ServerRequestInterface;
use React\EventLoop\Loop;
use React\Http\Message\Response;
use React\Stream\ThroughStream;
require __DIR__ . '/../vendor/autoload.php';
$http = new React\Http\HttpServer(function (ServerRequestInterface $request) {
if ($request->getMethod() !== 'GET' || $request->getUri()->getPath() !== '/') {
return new Response(404);
}
$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);
});
// demo for ending stream after a few seconds
Loop::addTimer(5.0, function() use ($stream) {
$stream->end();
});
// stop timer if stream is closed (such as when connection is closed)
$stream->on('close', function () use ($timer) {
Loop::cancelTimer($timer);
});
return new Response(
200,
array(
'Content-Type' => 'text/plain'
),
$stream
);
});
$socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '0.0.0.0:0');
$http->listen($socket);
echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL;