Skip to content

Instantly share code, notes, and snippets.

@mpociot
Last active January 20, 2021 05:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mpociot/443f9a525a70aea6942bcd1a37a2bb52 to your computer and use it in GitHub Desktop.
Save mpociot/443f9a525a70aea6942bcd1a37a2bb52 to your computer and use it in GitHub Desktop.
Simple ReactPHP chat server - connect to it: nc laracon.beyondco.de 8000
{
"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"
}
}
<?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