forked from reactphp/http
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04-stream-request.php
More file actions
44 lines (36 loc) · 1.48 KB
/
04-stream-request.php
File metadata and controls
44 lines (36 loc) · 1.48 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
<?php
use React\EventLoop\Factory;
use React\Socket\Server;
use React\Http\Response;
use Psr\Http\Message\ServerRequestInterface;
use React\Promise\Promise;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
$socket = new Server(isset($argv[1]) ? $argv[1] : '0.0.0.0:0', $loop);
$server = new \React\Http\Server($socket, function (ServerRequestInterface $request) {
return new Promise(function ($resolve, $reject) use ($request) {
$contentLength = 0;
$request->getBody()->on('data', function ($data) use (&$contentLength) {
$contentLength += strlen($data);
});
$request->getBody()->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
$request->getBody()->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);
});
});
});
echo 'Listening on http://' . $socket->getAddress() . PHP_EOL;
$loop->run();