|
| 1 | +<?php |
| 2 | + |
| 3 | +// Just start this server and connect with any number of clients to it. |
| 4 | +// Everything a client sends will be broadcasted to all connected clients. |
| 5 | +// |
| 6 | +// $ php examples/02-chat-server.php 8000 |
| 7 | +// $ telnet localhost 8000 |
| 8 | + |
| 9 | +use React\EventLoop\Factory; |
| 10 | +use React\Socket\Server; |
| 11 | +use React\Socket\ConnectionInterface; |
| 12 | + |
| 13 | +require __DIR__ . '/../vendor/autoload.php'; |
| 14 | + |
| 15 | +$loop = Factory::create(); |
| 16 | + |
| 17 | +$server = new Server($loop); |
| 18 | +$server->listen(isset($argv[1]) ? $argv[1] : 0, '0.0.0.0'); |
| 19 | + |
| 20 | +$clients = array(); |
| 21 | + |
| 22 | +$server->on('connection', function (ConnectionInterface $client) use (&$clients) { |
| 23 | + // keep a list of all connected clients |
| 24 | + $clients []= $client; |
| 25 | + $client->on('close', function() use ($client, &$clients) { |
| 26 | + unset($clients[array_search($client, $clients)]); |
| 27 | + }); |
| 28 | + |
| 29 | + // whenever a new message comes in |
| 30 | + $client->on('data', function ($data) use ($client, &$clients) { |
| 31 | + // remove any non-word characters (just for the demo) |
| 32 | + $data = trim(preg_replace('/[^\w\d \.\,\-\!\?]/u', '', $data)); |
| 33 | + |
| 34 | + // ignore empty messages |
| 35 | + if ($data === '') { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + // prefix with client IP and broadcast to all connected clients |
| 40 | + $data = $client->getRemoteAddress() . ': ' . $data . PHP_EOL; |
| 41 | + foreach ($clients as $client) { |
| 42 | + $client->write($data); |
| 43 | + } |
| 44 | + }); |
| 45 | +}); |
| 46 | + |
| 47 | +echo 'Listening on ' . $server->getPort() . PHP_EOL; |
| 48 | + |
| 49 | +$loop->run(); |
0 commit comments