forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09-stream-request.php
More file actions
54 lines (45 loc) · 1.86 KB
/
Copy path09-stream-request.php
File metadata and controls
54 lines (45 loc) · 1.86 KB
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
<?php
use Psr\Http\Message\ServerRequestInterface;
use React\EventLoop\Factory;
use React\Http\Response;
use React\Http\StreamingServer;
use React\Promise\Promise;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
// Note how this example uses the advanced `StreamingServer` 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 StreamingServer(function (ServerRequestInterface $request) {
return new Promise(function ($resolve, $reject) use ($request) {
$contentLength = 0;
$requestBody = $request->getBody();
$requestBody->on('data', function ($data) use (&$contentLength) {
$contentLength += strlen($data);
});
$requestBody->on('end', function () use ($resolve, &$contentLength){
$response = new Response(
200,
array(
'Content-Type' => 'text/plain'
),
"The length of the submitted request body is: " . $contentLength
);
$resolve($response);
});
// an error occures e.g. on invalid chunked encoded data or an unexpected 'end' event
$requestBody->on('error', function (\Exception $exception) use ($resolve, &$contentLength) {
$response = new Response(
400,
array(
'Content-Type' => 'text/plain'
),
"An error occured while reading at length: " . $contentLength
);
$resolve($response);
});
});
});
$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();