public function testDealerRep() { $pids[] = $this->forkRepWorker(); $pids[] = $this->forkRepWorker(); $loop = new StreamSelectLoop(); $context = new Context($loop); $dealer = $context->getSocket(\ZMQ::SOCKET_DEALER); $dealer->bind('ipc://test2.ipc'); sleep(1); $msgs = array(); $dealer->on('message', function ($msg) use(&$msgs) { $msgs[] = $msg; }); $dealer->send(array('A', '', 'foo')); $dealer->send(array('B', '', 'bar')); $loop->addTimer(1, function () use($loop) { $loop->stop(); }); $loop->run(); foreach ($pids as $pid) { pcntl_waitpid($pid, $status, WUNTRACED); } $this->assertCount(2, $msgs); $this->assertContains(array('A', '', 'foobar'), $msgs); $this->assertContains(array('B', '', 'barbar'), $msgs); }
public function setUp() { $this->port = !empty($GLOBALS['port']) ? (int) $GLOBALS['port'] : 8080; $this->loop = Factory::create(); $this->server = new Server($this->loop, $this->port, $this->path); $loop = $this->loop; $this->loop->addPeriodicTimer(10, function () use($loop) { $loop->stop(); }); }
public function run($port) { self::$port = $port; $loop = new StreamSelectLoop(); $socket = new SocketServer($loop); $http = new HttpServer($socket, $loop); $http->on('request', [$this, 'serve']); $socket->listen($port); echo "Reactavel server started on localhost:{$port}\n"; $loop->run(); }
/** * @covers React\EventLoop\StreamSelectLoop::tick */ public function testConnectionWithManyClients() { stream_socket_client('tcp://localhost:' . $this->port); stream_socket_client('tcp://localhost:' . $this->port); stream_socket_client('tcp://localhost:' . $this->port); $called = 0; $this->server->on('connection', function () use(&$called) { $called++; }); $this->loop->tick(); $this->loop->tick(); $this->loop->tick(); static::assertEquals(3, $called); }
/** * Connects to ProcessManager, master process. */ public function run() { $this->loop = \React\EventLoop\Factory::create(); $this->errorLogger = BufferingLogger::create(); ErrorHandler::register(new ErrorHandler($this->errorLogger)); $client = stream_socket_client($this->config['controllerHost']); $this->controller = new \React\Socket\Connection($client, $this->loop); $pcntl = new \MKraemer\ReactPCNTL\PCNTL($this->loop); $pcntl->on(SIGTERM, [$this, 'shutdown']); $pcntl->on(SIGINT, [$this, 'shutdown']); register_shutdown_function([$this, 'shutdown']); $this->bindProcessMessage($this->controller); $this->controller->on('close', \Closure::bind(function () { $this->shutdown(); }, $this)); $this->server = new React\Server($this->loop); //our version for now, because of unix socket support $http = new HttpServer($this->server); $http->on('request', array($this, 'onRequest')); //port is only used for tcp connection. If unix socket, 'host' contains the socket path $port = $this->config['port']; $host = $this->config['host']; while (true) { try { $this->server->listen($port, $host); break; } catch (\React\Socket\ConnectionException $e) { usleep(500); } } $this->sendMessage($this->controller, 'register', ['pid' => getmypid(), 'port' => $port]); $this->loop->run(); }
/** @test */ public function connectionToIp6TcpServerShouldSucceed() { $capturedStream = null; $loop = new StreamSelectLoop(); $server = new Server($loop); $server->on('connection', $this->expectCallableOnce()); $server->on('connection', array($server, 'shutdown')); $server->listen(9999, '::1'); $connector = new TcpConnector($loop); $connector->create('::1', 9999)->then(function ($stream) use(&$capturedStream) { $capturedStream = $stream; $stream->end(); }); $loop->run(); $this->assertInstanceOf('React\\Stream\\Stream', $capturedStream); }
/** * Returns the next free slave. This method is async, so be aware of async calls between this call. * * @return integer */ protected function getNextSlave($cb) { $that = $this; $checkSlave = function () use($cb, $that, &$checkSlave) { $minConnections = null; $minPort = null; foreach ($this->slaves as $slave) { if (!$slave['ready']) { continue; } if (!$this->concurrentRequestsPerWorker && $slave['busy']) { //we skip workers that are busy, means worker that are currently handle a connection //this makes it more robust since most applications are not made to handle //several request at the same time - even when one request is streaming. Would lead //to strange effects&crashes in high traffic sites if not considered. //maybe in the future this can be set application specific. //Rule of thumb: The application may not operate on globals, statics or same file paths to get this working. continue; } // we pick a slave that currently handles the fewest connections if (null === $minConnections || $slave['connections'] < $minConnections) { $minConnections = $slave['connections']; $minPort = $slave['port']; } } if (null !== $minPort) { $cb($minPort); return; } $this->loop->futureTick($checkSlave); }; $checkSlave(); }
public function testConnectFails() { $loop = new StreamSelectLoop(); $deferred = new Deferred(); $deferred->promise()->then(function () { $this->fail('should not have succeeded'); }, function ($value) use($loop) { $this->assertEquals(1, $value); $loop->stop(); }); $request = new RequestFactory(); $connector = new TcpConnector($loop); $client = new Client($connector, $request); $client->connect('127.0.0.1', 54320); $loop->run(); }
/** * @covers DNode\DNode::__construct * @covers DNode\DNode::connect * @covers DNode\DNode::listen * @test */ public function transformerShouldRespondCorrectly() { $captured = null; $loop = new StreamSelectLoop(); $server = new DNode($loop, new Transformer()); $socket = $server->listen(5004); $client = new DNode($loop); $client->connect(5004, function ($remote, $conn) use(&$captured, $socket) { $remote->transform('fou', function ($transformed) use($conn, &$captured, $socket) { $captured = $transformed; $conn->end(); $socket->shutdown(); }); }); $loop->run(); $this->assertSame('FOO', $captured); }
/** * {@inheritDoc} * @see \Symfony\Component\Console\Command\Command::execute() */ protected function execute(InputInterface $input, OutputInterface $output) { // Start listenning $this->socket->listen($this->port, $this->host); // Periodically call determining if we should stop or not $this->loop->addPeriodicTimer($input->getOption('check-interval'), function () use($output) { if ($this->shouldExitCommand($output)) { $this->loop->stop(); $this->writeln($output, 'Event loop stopped:' . $this->port); $this->returnValue = 10; } }); // Main loop $this->writeln($output, 'Starting event loop:' . $this->port); $this->loop->run(); return $this->returnValue; }
private function setTimer() { $this->loop->addPeriodicTimer(1, function () { if ($this->getBridge() instanceof Bridges\TimerBridgeInterface) { $this->getBridge()->timer($this); } }); }
public function bye() { if ($this->connection->isWritable()) { $this->connection->write(json_encode(array('cmd' => 'unregister', 'pid' => getmypid()))); $this->connection->close(); } $this->loop->stop(); }
/** * @covers React\Socket\Connection::getRemoteAddress */ public function testGetRemoteAddress() { $loop = new StreamSelectLoop(); $server = new Server($loop); $server->listen(0); $class = new \ReflectionClass('React\\Socket\\Server'); $master = $class->getProperty('master'); $master->setAccessible(true); $client = stream_socket_client('tcp://localhost:' . $server->getPort()); $class = new \ReflectionClass('React\\Socket\\Connection'); $method = $class->getMethod('parseAddress'); $method->setAccessible(true); $servConn = new Connection($server->master, $loop); $mock = $this->expectCallableOnceWith($method->invokeArgs($servConn, array(stream_socket_get_name($master->getValue($server), false)))); $server->on('connection', function ($conn) use($mock) { $mock($conn->getRemoteAddress()); }); $loop->tick(); }
public function create() { $that = $this; //todo: speed variable $this->loop->addReadStream(STDIN, function ($stdin) use($that) { $input = trim(fgets($stdin)); if (in_array($input, Config::$commands)) { if ($input === 'exit') { exit; } else { $that->emit('action', [$input]); } } else { echo 'Unknown command' . PHP_EOL; } echo $that->prompt; }); echo $this->getAsciiArt(); echo PHP_EOL; echo $this->prompt; }
public function run() { while (true) { try { $this->loadAddresses(); //aby načetl nově generované adresy $this->client->open(); $this->loop->run(); } catch (\Exception $e) { $this->logger->err($e->getMessage()); } } }
/** * @see \Markdown\Service\RenderServiceInterface::render() */ public function render($input) { $key = hash('sha512', $input); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } $rendered = null; $this->dnode->connect($this->options->getHost(), $this->options->getPort(), function ($remote, $connection) use($input, &$rendered) { $remote->render($input, function ($output, $exception = null, $error = null) use(&$rendered, $connection) { if ($exception !== null) { $connection->end(); throw new Exception\RuntimeException(sprintf('Bridge threw exception "%s" with message "%s".', $exception, $error)); } $rendered = $output; $connection->end(); }); }); $this->loop->run(); if ($rendered === null) { throw new Exception\RuntimeException(sprintf('Broken pipe')); } $this->storage->setItem($key, $rendered); return $rendered; }
/** * Retry connecting to the transport */ public function retryConnection() { $options = $this->reconnectOptions; if ($this->attemptRetry === false) { return; } if ($options['max_retries'] <= $this->retryAttempts) { return; } $this->retryAttempts++; if ($this->retryTimer >= $options['max_retry_delay']) { $this->retryTimer = $options['max_retry_delay']; } elseif ($this->retryTimer == 0) { $this->retryTimer = $options['initial_retry_delay']; } else { $this->retryTimer = $this->retryTimer * $options['retry_delay_growth']; } $this->loop->addTimer($this->retryTimer, function () { $this->transportProvider->startTransportProvider($this, $this->loop); }); }
public function onDispatch2(MvcEvent $e) { $this->socket->on('connection', function (ConnectionInterface $conn) { $conn->on('data', function ($dataRaw) use($conn) { $dataRaw = trim($dataRaw); $data = Json::decode($dataRaw, Json::TYPE_ARRAY); if ($data['queueName'] == 'checkEngine') { return; } if (!isset($this->config[$data['queueName']])) { $this->debug("Bad queue name: " . $data['queueName'], ['debug-enable' => 1]); return; } $queueName = $data['queueName']; $this->checkWorkersCount($queueName); $process = $this->handleData($data, $dataRaw, $this->getQueueConfig($queueName), $conn); if (!$process) { return; } $this->processes[$queueName][] = $process; }); }); $this->loop->addPeriodicTimer(1, function ($timer) { $processes = []; foreach ($this->processes as $queueName => $queue) { /** @var Process $process */ foreach ($queue as $process) { if ($process->isRunning()) { $processes[$queueName][] = $process; } else { $this->printProcessOutput($queueName, $process); } } } $this->processes = $processes; }); $this->socket->listen(4000); $this->loop->run(); }
/** * Connects to ProcessManager, master process. */ public function run() { $this->loop = \React\EventLoop\Factory::create(); ErrorHandler::register(new ErrorHandler(new BufferingLogger())); $this->client = stream_socket_client('tcp://127.0.0.1:5500'); $this->connection = new \React\Socket\Connection($this->client, $this->loop); $this->connection->on('error', function ($data) { var_dump($data); }); $pcntl = new \MKraemer\ReactPCNTL\PCNTL($this->loop); $pcntl->on(SIGTERM, [$this, 'shutdown']); $pcntl->on(SIGINT, [$this, 'shutdown']); register_shutdown_function([$this, 'shutdown']); $this->bindProcessMessage($this->connection); $this->connection->on('close', \Closure::bind(function () { $this->shutdown(); }, $this)); $this->server = new \React\Socket\Server($this->loop); $this->server->on('error', function ($data) { var_dump($data); }); $http = new HttpServer($this->server); $http->on('request', array($this, 'onRequest')); $http->on('error', function ($data) { var_dump($data); }); $port = $this->config['port']; while (true) { try { $this->server->listen($port); break; } catch (\React\Socket\ConnectionException $e) { usleep(500); } } $this->sendMessage($this->connection, 'register', ['pid' => getmypid(), 'port' => $port]); $this->loop->run(); }
/** * Registers a periodically triggered status event. */ private function registerTimedEvents() { $this->reactLoop->addPeriodicTimer($this->config->getStatusLoopInterval(), function () { $memoryUsageMb = memory_get_usage(true) / 1024 / 1024; $this->runtimeStatistics->setMemoryUsageMb($memoryUsageMb); if ($memoryUsageMb > $this->config->getMemoryLimitMbWarn()) { $this->logger->warning("MemoryUsage: {$memoryUsageMb} MB."); } else { if ($memoryUsageMb > $this->config->getMemoryLimitMbInfo()) { $this->logger->info("MemoryUsage: {$memoryUsageMb} MB."); } } $memoryPeakUsageMb = memory_get_peak_usage(true) / 1024 / 1024; $this->runtimeStatistics->setMemoryPeakUsageMb($memoryPeakUsageMb); if ($memoryPeakUsageMb > $this->config->getMemoryPeakLimitMbWarn()) { $this->logger->warning("MemoryPeakUsage " . memory_get_peak_usage(true) / 1024 / 1024 . " MB."); } $rateObjects = $this->runtimeStatistics->getAddedObjectRate($this->config->getStatusLoopInterval()); $rateEvictions = $this->runtimeStatistics->getEvictionRate($this->config->getStatusLoopInterval()); $this->logger->info("Added objects: {$this->runtimeStatistics->getAddedObjectCount()}, evictions: {$this->runtimeStatistics->getEvictedObjectCount()} ({$rateObjects} Obj/Sec, {$rateEvictions} Evi/Sec)."); $this->runtimeStatistics->tick(); }); }
public function run() { $this->loop->run(); }
function loop() { $this->loop->run(); }
/** * @return Client */ public function run() : Client { $this->loop->run(); return $this; }
/** * */ public function stop() { $this->loop->stop(); }
<?php use React\Stream\Stream; use React\EventLoop\Factory; use Clue\React\Tar\Decoder; use React\Stream\BufferedSink; use Clue\Hexdump\Hexdump; use React\EventLoop\StreamSelectLoop; require __DIR__ . '/../vendor/autoload.php'; $in = isset($argv[1]) ? $argv[1] : __DIR__ . '/../tests/fixtures/alice-bob.tar'; echo 'Reading file "' . $in . '" (pass as argument to example)' . PHP_EOL; // using the default loop does *not* work for file I/O //$loop = Factory::create(); $loop = new StreamSelectLoop(); $stream = new Stream(fopen($in, 'r'), $loop); $decoder = new Decoder(); $decoder->on('entry', function ($header, $file) { static $i = 0; echo 'FILE #' . ++$i . PHP_EOL; echo 'Received entry headers:' . PHP_EOL; var_dump($header); BufferedSink::createPromise($file)->then(function ($contents) { echo 'Received entry contents (' . strlen($contents) . ' bytes)' . PHP_EOL; $d = new Hexdump(); echo $d->dump($contents) . PHP_EOL . PHP_EOL; }); }); $decoder->on('error', function ($error) { echo 'ERROR: ' . $error . PHP_EOL; }); $decoder->on('close', function () {
public function testReturnsResponse() { $loop = new StreamSelectLoop(); $request = new RequestFactory(); $server = new Server($loop); $server->on('connection', function (SocketConnection $connection) use($server, $request) { $connection->on('data', function ($data) use($connection, $request) { $req = $request->response($data); $response = new Response($req->getId(), ['1.0']); $connection->write($response->write()); }); $connection->on('close', function () use($server) { $server->shutdown(); }); }); $server->listen(54323, '127.0.0.1'); $tcp = new TcpConnector($loop); $client = new Client($tcp, $request); $client->connect('127.0.0.1', 54323)->then(function (Connection $connection) use($loop) { $deferred = new Deferred(); $deferred->promise()->then(function ($value) { $this->assertEquals(1, $value); }); $electrum = new ElectrumClient($connection); $electrum->getServerVersion('1.9.6', ' 0.6')->then(function () use($deferred, $connection) { $deferred->resolve(1); $connection->close(); }, function () use($loop) { $loop->stop(); $this->fail(); }); }); $loop->run(); }
/** * */ public function run() { $this->reactLoop->run(); }
public function start() { $this->loop->run(); }