Created
January 11, 2019 07:09
-
-
Save sangheonhan/3542ff0afb493dc8cc8c65ab4e25a6f8 to your computer and use it in GitHub Desktop.
React Echo Server Example
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 | |
require 'vendor/autoload.php'; | |
$loop = React\EventLoop\Factory::create(); | |
$dnsResolverFactory = new React\Dns\Resolver\Factory(); | |
$dns = $dnsResolverFactory->createCached('8.8.8.8', $loop); | |
$connector = new React\SocketClient\Connector($loop, $dns); | |
$connector->create('127.0.0.1', 1337)->then( | |
function (React\Stream\Stream $stream) use ($loop) { | |
$i = 0; | |
$loop->addPeriodicTimer(1, function(React\EventLoop\Timer\Timer $timer) use (&$i, $loop, $stream) { | |
$stream->write(++$i . PHP_EOL); | |
if ($i >= 15) { | |
$loop->cancelTimer($timer); | |
$stream->close(); | |
} | |
}); | |
$stream->on('data', function ($data) { | |
echo $data; | |
}); | |
} | |
); | |
$loop->run(); |
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 | |
require 'vendor/autoload.php'; | |
$colours = ['red', 'green', 'yellow', 'blue', 'purple', 'cyan']; | |
$loop = React\EventLoop\Factory::create(); | |
$socket = new React\Socket\Server($loop); | |
// This event triggers every time a new connection comes in | |
$socket->on('connection', function ($conn) use ($colours) { | |
$colour = array_pop($colours); // Only doing this as an example, you will run out of colours. | |
// Event listener for incoming data | |
$conn->on('data', function ($data, $conn) use ($colour) { | |
// Write data back to the connection | |
$conn->write($data); | |
// Echo the data into our terminal window | |
echo (new \Malenki\Ansi($data))->fg($colour); | |
}); | |
}); | |
// Listen on port 1337 | |
$socket->listen(1337); | |
$loop->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment