/** * Execute the console command. * * @return void */ public function fire() { echo 'Iniciando servidor...' . PHP_EOL; $totalUsers = User::count(); $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); $socket->on('connection', function ($conn) use($totalUsers) { echo 'Enviando mensagem...' . PHP_EOL; $users = $this->getUsers($totalUsers / 2, $totalUsers / 2); $conn->end(serialize($users)); echo 'Enviada' . PHP_EOL; }); $socket->listen(1337); $loop->run(); }
public function actionRun() { $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); $socket->on('connection', function ($conn) { $conn->write("Hello there!\n"); $conn->write("Welcome to this amazing server!\n"); $conn->write("Here's a tip: don't say anything.\n"); $conn->on('data', function ($data) use($conn) { $conn->close(); }); }); $socket->listen(1337); $loop->run(); }
protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Start socket server'); $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); $socket->on('connection', function ($conn) { echo 'New client !' . "\n"; $conn->write("Hello there!\n"); $conn->write("Welcome to this server!\n"); $conn->on('data', function ($data) use($conn) { echo $data . "\n"; $conn->write($data); }); }); $socket->listen(4001); $loop->run(); }
public function start(Output\OutputInterface $output) { /* @var $_loop \React\EventLoop\LoopInterface*/ $loop = \React\EventLoop\Factory::create(); // create a new socket $socket = new \React\Socket\Server($loop); // pipe a connection into itself $socket->on('connection', function (\React\Socket\Connection $conn) use($output) { $output->writeln('CONNECTION ESTABLISHED: ' . $conn->getRemoteAddress()); $conn->pipe($conn); $conn->on('data', function ($data) use($conn, $output) { $conn->write('some additional information from data-event-handler ...'); $output->writeln("Server received: {$data}"); }); }); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen(4000); $loop->run(); }
public function start(Output\OutputInterface $output) { /* @var $_loop \React\EventLoop\LoopInterface*/ $loop = \React\EventLoop\Factory::create(); // create a new socket $socket = new \React\Socket\Server($loop); // pipe a connection into itself $socket->on('connection', function (\React\Socket\Connection $conn) use($output, $loop) { $output->writeln('CONNECTION ESTABLISHED: ' . $conn->getRemoteAddress()); //$infiniteStreamHandle = fopen('/tmp/random', 'r'); $infiniteStreamHandle = fopen('/dev/urandom', 'r'); $fileToStream = new \React\Stream\Stream($infiniteStreamHandle, $loop); $output->writeln('streaming ...'); //$conn->pipe($infiniteStreamHandle); $fileToStream->pipe($conn); }); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen(4000); $loop->run(); }
function run() { $this->before(); $port = $this->setting['port']; Load::file(MAIN_DIR . DS . 'vendor' . DS . 'autoload.php'); $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $conns = new \SplObjectStorage(); $this->connectionList =& $conns; $socket->on('connection', function ($conn) use($conns) { $this->onConnection($conn); $conns->attach($conn); $this->console('Attach new connection.'); $conn->on('data', function ($data) use($conns, $conn) { $this->onMessage($conn, $data); // foreach ($conns as $current) { // if ($conn !== $current) { // continue; // } // // $this->onMessage($conn, $data); // } }); $conn->on('end', function () use($conns, $conn) { $this->onClose($conn); $this->console('Detach connection.'); $conns->detach($conn); }); }); $this->console('Socket server listening on port ' . $port); $socket->listen($port); $loop->addPeriodicTimer($this->setting['timer'], function ($timer) use($conns) { $this->onTick($timer); }); $loop->run(); }
protected function execute(InputInterface $input, OutputInterface $output) { $timer = new \Svengerlach\Flake\Timer(); $sequencer = new \Svengerlach\Flake\Sequencer(); $generator = new \Svengerlach\Flake\Generator($timer, $sequencer, $input->getOption('epoch-start'), $input->getOption('node-identifier')); $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); $socket->on('connection', function (\React\Socket\Connection $conn) use($generator) { $conn->on('data', function ($data) use($conn, $generator) { $data = trim($data); if (0 !== strpos($data, 'GET ')) { return $conn->close(); } $parameter = substr($data, 4); for ($i = 0; $i < (int) $parameter; $i++) { $flake = $generator->generate(); $conn->write($flake . "\n"); } $conn->end(); }); }); $socket->listen($input->getOption('port'), $input->getOption('ip')); $loop->run(); }
<?php // serve a lot of data over TCP // useful for profiling // you can run this command to profile with xdebug: // php -d xdebug.profiler_enable=on examples/pump-shitload-of-data.php require __DIR__ . '/../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $socket->on('connection', function ($conn) { $shitload = str_repeat('a', 1024 * 1024 * 32); $conn->write($shitload); $conn->end(); }); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen(4000); $loop->run();
<?php require __DIR__ . '/../vendor/autoload.php'; use React\Socket\Connection; use ShortFlake\IdGenerator; $loop = React\EventLoop\Factory::create(); $id_generator = new IdGenerator($loop); // id socket $id_socket = new React\Socket\Server($loop); $id_socket->listen(1337); $id_socket->on('connection', function (Connection $conn) use($id_generator) { $id_generator->computeId()->then(function ($uuid) use($conn) { // uuid is an integer $conn->end($uuid); }); }); // metric socket $metric_socket = new React\Socket\Server($loop); $metric_socket->listen(1338); $metric_socket->on('connection', function (Connection $conn) use($id_generator) { $mem = memory_get_usage(TRUE); $conn->write('No of Ids: ' . $id_generator->getTotalGeneratedIds() . PHP_EOL); $conn->write('Mem Usage: ' . $mem . 'Bytes, ' . round($mem / 1024 / 104) . 'M' . PHP_EOL); $conn->end(); }); $loop->run();
<?php include "vendor/autoload.php"; ini_set("error_reporting", E_ALL); $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $conns = new \SplObjectStorage(); $i = 0; $socket->on('connection', function ($conn) use($conns, &$i) { $conns->attach($conn); $conn->on('data', function ($data) use($conn, &$conns) { $fastcgi_conn = new QFastCGI\Connection(); $fastcgi_conn->setData($data); $fastcgi_conn->onRead(); $conn->write("finish"); //$conn->write($fastcgi_conn->getAnswer()); }); $conn->on('end', function () use(&$conns, $conn, &$file) { $conns->detach($conn); }); }); $socket->listen(9900); $loop->run();
<?php require __DIR__ . '/../../vendor/autoload.php'; $reactor = (new Alert\ReactorFactory())->select(); $loop = (new Loopio\LoopFactory())->createReactLoop($reactor); $socket = new React\Socket\Server($loop); $i = 0; $socket->on('connection', function ($conn) use(&$i, $loop) { $i++; $conn->on('end', function () use(&$i) { $i--; }); }); $loop->addPeriodicTimer(2, function () use(&$i) { echo "{$i} open connections?\n"; }); $socket->listen(8080); $loop->run();
<?php // nc localhost 4000 use React\Chatroulette\AppInterface; use React\Chatroulette\LoggingApp; use React\Chatroulette\PairApp; use React\Chatroulette\TextApp; require 'vendor/autoload.php'; $logger = new Monolog\Logger('chatroulette'); $logger->pushHandler(new Monolog\Handler\StreamHandler(STDOUT)); $app = new LoggingApp(new TextApp(new PairApp()), $logger); $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $i = 0; $names = ['Alice', 'Bob', 'Carol', 'Dave', 'Erin', 'Frank', 'Eve', 'Mallory', 'Oscar', 'Peggy', 'Trent', 'Walter']; $socket->on('connection', function ($conn) use(&$i, $names, $app) { $conn->id = isset($names[$i]) ? $names[$i] : $i; $app->connect($conn); $i++; }); $socket->listen(4000); $loop->run();
<?php use cebe\pulse\discover\Address; use cebe\pulse\discover\Device; use cebe\pulse\discover\DiscoveryManager; use cebe\pulse\discover\Packet; require __DIR__ . '/vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); // config // generates a random node ID, should be replaced with a real hash of the TLS cert $id = rtrim(\Base32\Base32::encode(hash('sha256', rand() . microtime(true), true)), '='); $servicePort = rand(1337, 32000); // setup $discoveryManager = new DiscoveryManager($id); $discoveryManager->servicePort = $servicePort; $discoveryManager->start($loop); // TCP Server $socket = new React\Socket\Server($loop); $socket->on('connection', function ($conn) { // $conn->write("Hello there!\n"); // $conn->write("Welcome to this amazing server!\n"); // $conn->write("Here's a tip: don't say anything.\n"); echo "connection from " . $conn->getRemoteAddress() . "\n"; $conn->on('data', function ($data) use($conn) { echo "{$data}\n"; $conn->close(); }); }); $socket->listen($servicePort); $loop->run();
} /** Create kettle stream listener and handle response data */ $kettle->getStream()->on('data', function ($data) use($kettle) { $kettle->handleResponse($data); print_r($kettle->getState()); }); /** Create a socket listener */ $socket = new React\Socket\Server($loop); $socket->on('connection', function (React\Socket\Connection $connection) use($kettle) { echo "\n==== New conenction ====\n\n"; $connection->write("\nKettle commands:\n- boil\n- off\n\n"); /** Create socket data listener */ $connection->on('data', function ($data, $conn) use($kettle) { switch ($kettle->sanitizeResponse($data)) { case 'boil': $connectionMessage = 'Kettle was boiled'; $kettle->boil(); break; case 'off': $connectionMessage = 'Kettle was turned off'; $kettle->off(); break; default: $connectionMessage = 'Command was not recognized'; break; } $conn->write("=> {$connectionMessage}\n\n"); }); }); $socket->listen(1336); $loop->run();
$logger->debug('Instantiating main Chat object'); $chat = new Chat(); // this is our TCP-server that will receive messages // to be delivered to clients/browsers via websocket; $logger->debug('Instantiating main "Server" socket object'); $server = new React\Socket\Server($loop); // Let's define some very-basic code to be run when something is // received on the main socket (the one supposed to RECEIVE the // data to be sent to websocket clients... $logger->debug('Setting [onConnection/onData] callback'); $server->on('connection', function ($conn) use($chat, $logger) { $logger->info('[onConnection] New client connected'); //I'm not going to broadcast anything, as it's not a JSON-formattted data to be shown on dashboard //$chat->broadcast ( "[onCONNECTION] Client arrivato..." . PHP_EOL ); // Please note that the onDATA callback is defined INSIDE the outer onCONNECTION one! $conn->on('data', function ($data) use($conn, $chat, $logger) { $logger->debug('[onData] Got data from socket [' . $data . ' bytes]'); // passo ai client un JSON "puro", altrimenti genero problemi di parsing... $chat->broadcast($data . PHP_EOL); //$conn->write("I just got: [".$data."]"); }); }); // Let's run the main server socket $logger->debug('Spinning main server socket'); $server->listen(1337, '0.0.0.0'); // Let's run the main websocket $logger->debug('Instantiating main WebSocket object'); $webSock = new React\Socket\Server($loop); $logger->debug('Spinning main websocket'); $webSock->listen(8888, '0.0.0.0'); // This is not clear... (to me, at least), unfortunately !!!! $logger->debug('instantiating main webserver (?)');
$conn->on('close', [$this, 'onClose']); } public function onData($data) { // Write data that came in from this connection into all connection foreach ($this->connections as $connection) { $connection->write($data); } // Echo the data into our terminal window echo (new Malenki\Ansi($data))->fg($this->colour); } public function onClose($conn) { $this->connections->detach($conn); } } require 'vendor/autoload.php'; $colours = ['red', 'green', 'yellow', 'blue', 'purple', 'cyan']; $connections = new \SplObjectStorage(); $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, $connections) { $colour = array_pop($colours); // Only doing this as an example, you will run out of colours. // Instancing a new connection object per connection new Connection($conn, $colour, $connections); }); // Listen on port 1337 $socket->listen(1337); $loop->run();
<?php require 'vendor/autoload.php'; $app = new \Testify\Testify(new \Testify\CommandHandler()); $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($app) { $conn->write($app->welcome()); $conn->on('data', function ($data, $conn) use($app) { $app->handle($data, $conn); }); }); // Listen on port 1337 $socket->listen(1337); $loop->run();
<?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();
<?php // socket based chat require __DIR__ . '/../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $conns = new \SplObjectStorage(); $socket->on('connection', function ($conn) use($conns) { $conns->attach($conn); $conn->on('data', function ($data) use($conns, $conn) { foreach ($conns as $current) { if ($conn === $current) { continue; } $current->write($conn->getRemoteAddress() . ': '); $current->write($data); } }); $conn->on('end', function () use($conns, $conn) { $conns->detach($conn); }); }); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen(4000); $loop->run();
$port = array_key_exists(2, $argv) ? $argv[2] : 1337; $dbh = new \PDO('sqlite:' . __DIR__ . '/../data/games'); $repository = new \Wecamp\FlyingLiquorice\Storage\SqliteGameRepository($dbh); $socket->on('connection', function ($conn) use($conns, $repository) { $conn->id = ''; $conns->attach($conn); $conn->write(PHP_EOL . PHP_EOL); $conn->write(showShip() . PHP_EOL); $conn->write('WELCOME TO BATTLESHIP' . PHP_EOL); $conn->write(PHP_EOL . PHP_EOL); $conn->write('Use `help` to see all available commands' . PHP_EOL); $conn->on('data', function ($data) use($conns, $conn, $repository) { foreach ($conns as $current) { if ($conn === $current) { $service = new \Wecamp\FlyingLiquorice\Service\ServiceListener($data, $conn->id, $repository); try { $current->write($service->run() . PHP_EOL); $conn->id = (string) $service->id(); } catch (\InvalidArgumentException $e) { $current->write('ERROR ' . get_class($e) . PHP_EOL); } } } }); $conn->on('end', function () use($conns, $conn) { $conns->detach($conn); }); }); try { $socket->listen($port, $ip); echo 'Socket server listening on port ' . $port . ".\n";
<?php require "vendor/autoload.php"; $loop = React\EventLoop\Factory::create(); $server = new \React\Socket\Server($loop); $server->on('connection', function (\React\Stream\Stream $stream) { $stream->on('data', function ($data) use($stream) { if ($data == 'say hi!') { echo "client sent somethiing\n"; echo "msg: {$data}\n"; $stream->write('Hi back!'); } }); echo "Inbound connection: " . PHP_EOL; //$stream->write('hello from server!'); }); $server->listen(1234); $loop->run();
<?php require dirname(__DIR__) . '/vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $socket->on('connection', function ($conn) { echo "===> [CONNECT]<====\n"; $conn->write("Hello there!\n"); $conn->write("Welcome to this amazing server!\n"); $conn->write("Here's a tip: don't say anything.\n"); $conn->on('data', function ($data) { echo "===> [" . $data . "]<====\n"; }); }); $socket->listen(1337); $loop->run();
//Init the event loop class $socket = new React\Socket\Server($loop); //Init the socket server class $db = new PDO('sqlite::memory:'); //Init PDO SQLite into memory $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); createMediaTable(); //Create the media table mapDirContentsToDB(); //Insert the initial list of file into the media table /* Create the socket */ $socket->on('connection', function ($conn) use($loop, $PUSH_TIMER) { $loop->addPeriodicTimer($PUSH_TIMER, function () use($conn) { $media = getMedia(); //Get Semi-Random Media file to push through the socket $conn->write($media); //Push Media through socket to the client updateMediaViews($media); //Update the media table to reflect that this media item has been sent. }); }); /* watch the dir for new images */ $loop->addPeriodicTimer($WATCH_DIR_TIMER, function () { mapDirContentsToDB(); }); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen($SOCKET_PORT); //Start the socket lisining on port 400 $loop->run(); //Start the event loop //Helper methods ----------------------------------------------------------------------------------------------
/** * The thread's run() method that runs asynchronously. * * @return void * @link http://www.php.net/manual/en/thread.run.php */ public function run() { // register a shutdown handler for controlled shutdown register_shutdown_function(array(&$this, 'shutdown')); // we need the autloader again require SERVER_AUTOLOADER; // create a reference to the application server instance $applicationServer = $this->applicationServer; // initialize the event loop and the socket server $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); // wait for connections $socket->on('connection', function ($conn) use($applicationServer) { // write the appserver.io logo to the console $conn->write(Telnet::$logo); $conn->write("\$ "); // wait for user input => usually a command $conn->on('data', function ($data) use($conn, $applicationServer) { try { // extract command name and parameters list($commandName, ) = explode(' ', $data); $params = explode(' ', trim(substr($data, strlen($commandName)))); // initialize and execute the command $command = CommandFactory::factory(trim($commandName), array($conn, $applicationServer)); $command->execute($params); } catch (\ReflectionException $re) { $conn->write("Unknown command {$commandName}"); } catch (\Exception $e) { $conn->write($e->__getMessage()); } // write the command prompt $conn->write("\$ "); }); }); // listen to the management socket $socket->listen($this->getPort(), $this->getAddress()); // start the event loop and the socket server, but disable warnings as some React warnings cannot (or won't) be dealt with. // Specifically the warning if a client disconnects unexpectedly or does not even connect to begin with ("Interrupted system call") is unevitable // @see https://github.com/reactphp/react/pull/297 // @see https://github.com/reactphp/react/issues/296 // @see http://php.net/manual/de/function.stream-select.php $currentReportingLevel = error_reporting(); error_reporting(E_ALL ^ E_WARNING); $loop->run(); error_reporting($currentReportingLevel); }
<?php // pipe a connection into itself require __DIR__ . '/../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $socket->on('connection', function ($conn) { $conn->pipe($conn); }); echo "Socket server listening on port 4000.\n"; echo "You can connect to it by running: telnet localhost 4000\n"; $socket->listen(4000); $loop->run();
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void Script exit code */ protected function execute(InputInterface $input, OutputInterface $output) { $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); $server = $this->server; $socket->on('connection', function ($connection) use($server) { $name = ''; $connection->on('data', function ($data) use(&$name, $server, $connection) { if ($name) { return; } $name = trim($data); $server->addSocketConnection($connection, $name); }); }); $socket->listen(1337, '0.0.0.0'); //http server $webroot = $this->webroot; $detailsSocket = new \React\Socket\Server($loop); $http = new \React\Http\Server($detailsSocket); $gameToArray = function (\Connect4\Server\GameArchive\ArchivedGame $game) { $board = $game->getBoard(); $data = ['id' => $game->getId(), 'board' => [], 'redPlayer' => $game->getRedPlayerName(), 'yellowPlayer' => $game->getYellowPlayerName(), 'date' => $game->getDate()->format('Y-m-d H:i:s'), 'transcript' => [], 'state' => $board->getState()->getValue()]; foreach (range(\Connect4\Lib\Row::MIN, \Connect4\Lib\Row::MAX) as $rowNumber) { $rowContents = $board->getRowContents(new \Connect4\Lib\Row($rowNumber)); $cells = []; foreach ($rowContents as $cell) { $cells[] = (string) $cell; } $data['board'][] = $cells; } foreach ($board->getTranscript() as $move) { $data['transcript'][] = [$move->getPlayer()->getValue(), $move->getColumn()->getValue()]; } return $data; }; $http->on('request', function ($request, $response) use($server, $webroot, $gameToArray) { $serve = function ($content, $type, $code = 200) use($response) { $headers = array('Content-Type' => $type); $response->writeHead($code, $headers); $response->end($content); }; switch ($request->getPath()) { case '/archive': $query = $request->getQuery(); $archive = $server->getGameArchive(); if (isset($query['since'])) { $archivedGames = $archive->getArchiveSince($query['since']); } else { $archivedGames = $archive->getArchive(); } $games = []; foreach ($archivedGames as $i => $game) { $games[] = $gameToArray($game, $i + 1); } $serve(json_encode($games), 'application/json'); break; case '/': $serve(file_get_contents($webroot . '/index.html'), 'text/html'); break; case '/connect4.js': $serve(file_get_contents($webroot . '/connect4.js'), 'application/javascript'); break; case '/connect4.css': $serve(file_get_contents($webroot . '/connect4.css'), 'text/css'); break; default: $serve('Not Found', 'text/html', 404); break; } }); $detailsSocket->listen(8080, '0.0.0.0'); $loop->run(); }