forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path63-server-streaming-request.php
56 lines (45 loc) · 1.99 KB
/
63-server-streaming-request.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
45
46
47
48
49
50
51
52
53
54
55
56
<?php
use React\EventLoop\Factory;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
// Note how this example uses the advanced `StreamingRequestMiddleware` to allow streaming
// the incoming HTTP request. This very simple example merely counts the size
// of the streaming body, it does not otherwise buffer its contents in memory.
$server = new React\Http\Server(array(
new React\Http\Middleware\StreamingRequestMiddleware(),
function (Psr\Http\Message\ServerRequestInterface $request) {
$body = $request->getBody();
assert($body instanceof Psr\Http\Message\StreamInterface);
assert($body instanceof React\Stream\ReadableStreamInterface);
return new React\Promise\Promise(function ($resolve, $reject) use ($body) {
$bytes = 0;
$body->on('data', function ($data) use (&$bytes) {
$bytes += strlen($data);
});
$body->on('end', function () use ($resolve, &$bytes){
$resolve(new React\Http\Message\Response(
200,
array(
'Content-Type' => 'text/plain'
),
"Received $bytes bytes\n"
));
});
// an error occures e.g. on invalid chunked encoded data or an unexpected 'end' event
$body->on('error', function (\Exception $exception) use ($resolve, &$bytes) {
$resolve(new React\Http\Message\Response(
400,
array(
'Content-Type' => 'text/plain'
),
"Encountered error after $bytes bytes: {$exception->getMessage()}\n"
));
});
});
}
));
$server->on('error', 'printf');
$socket = new \React\Socket\Server(isset($argv[1]) ? $argv[1] : '0.0.0.0:0', $loop);
$server->listen($socket);
echo 'Listening on ' . str_replace('tcp:', 'http:', $socket->getAddress()) . PHP_EOL;
$loop->run();