02-chat-server.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. // Just start this server and connect with any number of clients to it.
  3. // Everything a client sends will be broadcasted to all connected clients.
  4. //
  5. // $ php examples/02-chat-server.php 127.0.0.1:8000
  6. // $ telnet localhost 8000
  7. //
  8. // You can also run a secure TLS chat server like this:
  9. //
  10. // $ php examples/02-chat-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/02-chat-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/02-chat-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 = new React\Socket\LimitingServer($socket, null);
  29. $socket->on('connection', function (React\Socket\ConnectionInterface $connection) use ($socket) {
  30. echo '[' . $connection->getRemoteAddress() . ' connected]' . PHP_EOL;
  31. // whenever a new message comes in
  32. $connection->on('data', function ($data) use ($connection, $socket) {
  33. // remove any non-word characters (just for the demo)
  34. $data = trim(preg_replace('/[^\w\d \.\,\-\!\?]/u', '', $data));
  35. // ignore empty messages
  36. if ($data === '') {
  37. return;
  38. }
  39. // prefix with client IP and broadcast to all connected clients
  40. $data = trim(parse_url($connection->getRemoteAddress(), PHP_URL_HOST), '[]') . ': ' . $data . PHP_EOL;
  41. foreach ($socket->getConnections() as $connection) {
  42. $connection->write($data);
  43. }
  44. });
  45. $connection->on('close', function () use ($connection) {
  46. echo '[' . $connection->getRemoteAddress() . ' disconnected]' . PHP_EOL;
  47. });
  48. });
  49. $socket->on('error', function (Exception $e) {
  50. echo 'Error: ' . $e->getMessage() . PHP_EOL;
  51. });
  52. echo 'Listening on ' . $socket->getAddress() . PHP_EOL;