91-benchmark-server.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. // Just start the server and connect to it. It will count the number of bytes
  3. // sent for each connection and will print the average throughput once the
  4. // connection closes.
  5. //
  6. // $ php examples/91-benchmark-server.php 127.0.0.1:8000
  7. // $ telnet localhost 8000
  8. // $ echo hello world | nc -N localhost 8000
  9. // $ dd if=/dev/zero bs=1M count=1000 | nc -N localhost 8000
  10. //
  11. // You can also run a secure TLS benchmarking server like this:
  12. //
  13. // $ php examples/91-benchmark-server.php tls://127.0.0.1:8000 examples/localhost.pem
  14. // $ openssl s_client -connect localhost:8000
  15. // $ echo hello world | openssl s_client -connect localhost:8000
  16. // $ dd if=/dev/zero bs=1M count=1000 | openssl s_client -connect localhost:8000
  17. //
  18. // You can also run a Unix domain socket (UDS) server benchmark like this:
  19. //
  20. // $ php examples/91-benchmark-server.php unix:///tmp/server.sock
  21. // $ nc -N -U /tmp/server.sock
  22. // $ dd if=/dev/zero bs=1M count=1000 | nc -N -U /tmp/server.sock
  23. //
  24. // You can also use systemd socket activation and listen on an inherited file descriptor:
  25. //
  26. // $ systemd-socket-activate -l 8000 php examples/91-benchmark-server.php php://fd/3
  27. // $ telnet localhost 8000
  28. // $ echo hello world | nc -N localhost 8000
  29. // $ dd if=/dev/zero bs=1M count=1000 | nc -N localhost 8000
  30. require __DIR__ . '/../vendor/autoload.php';
  31. $socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '127.0.0.1:0', array(
  32. 'tls' => array(
  33. 'local_cert' => isset($argv[2]) ? $argv[2] : (__DIR__ . '/localhost.pem')
  34. )
  35. ));
  36. $socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
  37. echo '[' . $connection->getRemoteAddress() . ' connected]' . PHP_EOL;
  38. // count the number of bytes received from this connection
  39. $bytes = 0;
  40. $connection->on('data', function ($chunk) use (&$bytes) {
  41. $bytes += strlen($chunk);
  42. });
  43. // report average throughput once client disconnects
  44. $t = microtime(true);
  45. $connection->on('close', function () use ($connection, $t, &$bytes) {
  46. $t = microtime(true) - $t;
  47. echo '[' . $connection->getRemoteAddress() . ' disconnected after receiving ' . $bytes . ' bytes in ' . round($t, 3) . 's => ' . round($bytes / $t / 1024 / 1024, 1) . ' MiB/s]' . PHP_EOL;
  48. });
  49. });
  50. $socket->on('error', function (Exception $e) {
  51. echo 'Error: ' . $e->getMessage() . PHP_EOL;
  52. });
  53. echo 'Listening on ' . $socket->getAddress() . PHP_EOL;