03-benchmark.php 1.8 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/03-benchmark.php 8000
  7. // $ telnet localhost 8000
  8. // $ echo hello world | nc -v localhost 8000
  9. // $ dd if=/dev/zero bs=1M count=1000 | nc -v localhost 8000
  10. //
  11. // You can also run a secure TLS benchmarking server like this:
  12. //
  13. // $ php examples/03-benchmark.php 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. use React\EventLoop\Factory;
  18. use React\Socket\Server;
  19. use React\Socket\ConnectionInterface;
  20. use React\Socket\SecureServer;
  21. require __DIR__ . '/../vendor/autoload.php';
  22. $loop = Factory::create();
  23. $server = new Server($loop);
  24. // secure TLS mode if certificate is given as second parameter
  25. if (isset($argv[2])) {
  26. $server = new SecureServer($server, $loop, array(
  27. 'local_cert' => $argv[2]
  28. ));
  29. }
  30. $server->listen(isset($argv[1]) ? $argv[1] : 0);
  31. $server->on('connection', function (ConnectionInterface $conn) use ($loop) {
  32. echo '[connected]' . PHP_EOL;
  33. // count the number of bytes received from this connection
  34. $bytes = 0;
  35. $conn->on('data', function ($chunk) use (&$bytes) {
  36. $bytes += strlen($chunk);
  37. });
  38. // report average throughput once client disconnects
  39. $t = microtime(true);
  40. $conn->on('close', function () use ($conn, $t, &$bytes) {
  41. $t = microtime(true) - $t;
  42. echo '[disconnected after receiving ' . $bytes . ' bytes in ' . round($t, 3) . 's => ' . round($bytes / $t / 1024 / 1024, 1) . ' MiB/s]' . PHP_EOL;
  43. });
  44. });
  45. $server->on('error', 'printf');
  46. echo 'bound to ' . $server->getPort() . PHP_EOL;
  47. $loop->run();