-
-
Save cmcintosh/8f34c1defd930dc3a5ceb8f383119c02 to your computer and use it in GitHub Desktop.
Simple ReactPHP chat server - connect to it: nc laracon.beyondco.de 8000
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"react/event-loop": "^1.1", | |
"react/stream": "^1.1", | |
"react/promise": "^2.8", | |
"react/socket": "^1.6", | |
"react/http": "^1.2", | |
"nubs/random-name-generator": "^2.2" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use React\Socket\ConnectionInterface; | |
require __DIR__ . '/vendor/autoload.php'; | |
$loop = \React\EventLoop\Factory::create(); | |
$server = new \React\Socket\Server('0.0.0.0:8000', $loop); | |
$limitingServer = new \React\Socket\LimitingServer($server, null); | |
$generator = new \Nubs\RandomNameGenerator\Alliteration(); | |
$limitingServer->on('connection', function (ConnectionInterface $connection) use ($limitingServer, $generator) { | |
echo "New connection from {$connection->getRemoteAddress()}".PHP_EOL; | |
$connection->name = $generator->getName(); | |
foreach ($limitingServer->getConnections() as $serverConnection) { | |
if ($connection->getRemoteAddress() !== $serverConnection->getRemoteAddress()) { | |
$serverConnection->write("New connection from ".$connection->name."\n"); | |
} | |
} | |
$connection->write("Hi 👋\nI hope you enjoyed my Laracon EU talk about ReactPHP!\nIf you can't get enough, you can watch a free video course on ReactPHP on our website at https://beyondco.de.\nFeel free to chat in here - there are ".count($limitingServer->getConnections())." other people > | |
$connection->on('data', function ($data) use ($connection, $limitingServer) { | |
echo $connection->getRemoteAddress().":{$data}"; | |
foreach ($limitingServer->getConnections() as $serverConnection) { | |
if ($connection->getRemoteAddress() !== $serverConnection->getRemoteAddress()) { | |
$serverConnection->write($connection->name.': '.$data); | |
} | |
} | |
}); | |
$connection->on('close', function () { | |
echo "Connection closed".PHP_EOL; | |
}); | |
}); | |
$loop->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment