02-chat-server.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 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 8000 examples/localhost.pem
  11. // $ openssl s_client -connect localhost:8000
  12. use React\EventLoop\Factory;
  13. use React\Socket\Server;
  14. use React\Socket\ConnectionInterface;
  15. use React\Socket\SecureServer;
  16. require __DIR__ . '/../vendor/autoload.php';
  17. $loop = Factory::create();
  18. $server = new Server($loop);
  19. // secure TLS mode if certificate is given as second parameter
  20. if (isset($argv[2])) {
  21. $server = new SecureServer($server, $loop, array(
  22. 'local_cert' => $argv[2]
  23. ));
  24. }
  25. $server->listen(isset($argv[1]) ? $argv[1] : 0, '0.0.0.0');
  26. $clients = array();
  27. $server->on('connection', function (ConnectionInterface $client) use (&$clients) {
  28. // keep a list of all connected clients
  29. $clients []= $client;
  30. $client->on('close', function() use ($client, &$clients) {
  31. unset($clients[array_search($client, $clients)]);
  32. });
  33. // whenever a new message comes in
  34. $client->on('data', function ($data) use ($client, &$clients) {
  35. // remove any non-word characters (just for the demo)
  36. $data = trim(preg_replace('/[^\w\d \.\,\-\!\?]/u', '', $data));
  37. // ignore empty messages
  38. if ($data === '') {
  39. return;
  40. }
  41. // prefix with client IP and broadcast to all connected clients
  42. $data = $client->getRemoteAddress() . ': ' . $data . PHP_EOL;
  43. foreach ($clients as $client) {
  44. $client->write($data);
  45. }
  46. });
  47. });
  48. $server->on('error', 'printf');
  49. echo 'Listening on ' . $server->getPort() . PHP_EOL;
  50. $loop->run();