forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
63-server-streaming-request.php
50 lines (42 loc) · 1.91 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
<?php
require __DIR__ . '/../vendor/autoload.php';
// 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.
$http = new React\Http\HttpServer(
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"
));
});
});
}
);
$http->on('error', 'printf');
$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;