|
| 1 | +<?php |
| 2 | + |
| 3 | +// Simple HTTP server example (for illustration purposes only). |
| 4 | +// This shows how a plaintext TCP/IP connection is accepted to then receive an |
| 5 | +// application level protocol message (HTTP request) and reply with an |
| 6 | +// application level protocol message (HTTP response) in return. |
| 7 | +// |
| 8 | +// This example exists for illustraion purposes only. It does not actually |
| 9 | +// parse incoming HTTP requests, so you can actually send *anything* and will |
| 10 | +// still respond with a valid HTTP response. |
| 11 | +// Real applications should use react/http instead! |
| 12 | +// |
| 13 | +// Just start this server and send a request to it: |
| 14 | +// |
| 15 | +// $ php examples/03-http-server.php 8000 |
| 16 | +// $ curl -v http://localhost:8000/ |
| 17 | +// $ ab -n1000 -c10 http://localhost:8000/ |
| 18 | +// $ docker run -it --rm --net=host jordi/ab ab -n1000 -c10 http://localhost:8000/ |
| 19 | +// |
| 20 | +// You can also run a secure HTTPS echo server like this: |
| 21 | +// |
| 22 | +// $ php examples/03-http-server.php tls://127.0.0.1:8000 examples/localhost.pem |
| 23 | +// $ curl -v --insecure https://localhost:8000/ |
| 24 | +// $ ab -n1000 -c10 https://localhost:8000/ |
| 25 | +// $ docker run -it --rm --net=host jordi/ab ab -n1000 -c10 https://localhost:8000/ |
| 26 | +// |
| 27 | +// You can also run a Unix domain socket (UDS) server like this: |
| 28 | +// |
| 29 | +// $ php examples/03-http-server.php unix:///tmp/server.sock |
| 30 | +// $ nc -U /tmp/server.sock |
| 31 | + |
| 32 | +use React\EventLoop\Factory; |
| 33 | +use React\Socket\Server; |
| 34 | +use React\Socket\ConnectionInterface; |
| 35 | + |
| 36 | +require __DIR__ . '/../vendor/autoload.php'; |
| 37 | + |
| 38 | +$loop = Factory::create(); |
| 39 | + |
| 40 | +$server = new Server(isset($argv[1]) ? $argv[1] : 0, $loop, array( |
| 41 | + 'tls' => array( |
| 42 | + 'local_cert' => isset($argv[2]) ? $argv[2] : (__DIR__ . '/localhost.pem') |
| 43 | + ) |
| 44 | +)); |
| 45 | + |
| 46 | +$server->on('connection', function (ConnectionInterface $conn) { |
| 47 | + $conn->once('data', function () use ($conn) { |
| 48 | + $body = "<html><h1>Hello world!</h1></html>\r\n"; |
| 49 | + $conn->end("HTTP/1.1 200 OK\r\nContent-Length: " . strlen($body) . "\r\nConnection: close\r\n\r\n" . $body); |
| 50 | + }); |
| 51 | +}); |
| 52 | + |
| 53 | +$server->on('error', 'printf'); |
| 54 | + |
| 55 | +echo 'Listening on ' . strtr($server->getAddress(), array('tcp:' => 'http:', 'tls:' => 'https:')) . PHP_EOL; |
| 56 | + |
| 57 | +$loop->run(); |
0 commit comments