01-echo-server.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. // Just start this server and connect to it. Everything you send to it will be
  3. // sent back to you.
  4. //
  5. // $ php examples/01-echo-server.php 127.0.0.1:8000
  6. // $ telnet localhost 8000
  7. //
  8. // You can also run a secure TLS echo server like this:
  9. //
  10. // $ php examples/01-echo-server.php tls://127.0.0.1:8000 examples/localhost.pem
  11. // $ openssl s_client -connect localhost:8000
  12. //
  13. // You can also run a Unix domain socket (UDS) server like this:
  14. //
  15. // $ php examples/01-echo-server.php unix:///tmp/server.sock
  16. // $ nc -U /tmp/server.sock
  17. //
  18. // You can also use systemd socket activation and listen on an inherited file descriptor:
  19. //
  20. // $ systemd-socket-activate -l 8000 php examples/01-echo-server.php php://fd/3
  21. // $ telnet localhost 8000
  22. require __DIR__ . '/../vendor/autoload.php';
  23. $socket = new React\Socket\SocketServer(isset($argv[1]) ? $argv[1] : '127.0.0.1:0', array(
  24. 'tls' => array(
  25. 'local_cert' => isset($argv[2]) ? $argv[2] : (__DIR__ . '/localhost.pem')
  26. )
  27. ));
  28. $socket->on('connection', function (React\Socket\ConnectionInterface $connection) {
  29. echo '[' . $connection->getRemoteAddress() . ' connected]' . PHP_EOL;
  30. $connection->pipe($connection);
  31. $connection->on('close', function () use ($connection) {
  32. echo '[' . $connection->getRemoteAddress() . ' disconnected]' . PHP_EOL;
  33. });
  34. });
  35. $socket->on('error', function (Exception $e) {
  36. echo 'Error: ' . $e->getMessage() . PHP_EOL;
  37. });
  38. echo 'Listening on ' . $socket->getAddress() . PHP_EOL;