当前位置: 首页>>代码示例>>PHP>>正文


PHP EventLoop\Factory类代码示例

本文整理汇总了PHP中React\EventLoop\Factory的典型用法代码示例。如果您正苦于以下问题:PHP Factory类的具体用法?PHP Factory怎么用?PHP Factory使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Factory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: fire

 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     echo 'Iniciado' . PHP_EOL;
     $start = microtime(true);
     $totalUsers = User::count();
     //cria o main loop
     $loop = \React\EventLoop\Factory::create();
     //cria a conexão MySQL
     $connection = new \React\MySQL\Connection($loop, array('dbname' => $_ENV['DB_DATABASE'], 'user' => $_ENV['DB_USERNAME'], 'passwd' => $_ENV['DB_PASSWORD']));
     $connection->connect(function () {
     });
     $query1 = '
         SELECT * FROM users
             LEFT JOIN companies ON users.company_id = companies.id
         LIMIT ' . $totalUsers / 2 . '
     ;';
     $query2 = '
         SELECT * FROM users
             LEFT JOIN companies ON users.company_id = companies.id
         LIMIT ' . $totalUsers / 2 . '
         OFFSET ' . $totalUsers / 2 . '
     ;';
     $this->getUsers($connection, $query1, $loop);
     $this->getUsers($connection, $query2, $loop);
     $loop->run();
     echo 'Processados ' . count($this->users) . ' usuários' . PHP_EOL;
     echo 'Demorou ' . number_format((microtime(true) - $start) * 1000, 2, ',', '') . 'ms' . PHP_EOL;
 }
开发者ID:beingsane,项目名称:SeminarioLocaweb,代码行数:33,代码来源:BuildReactCommand.php

示例2: fire

 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     // create a log channel
     $log = new Logger('websocket');
     $log->pushHandler(new RotatingFileHandler(storage_path() . '/logs/websocket.log', 10, Logger::DEBUG));
     $config = Config::get('announcements-server');
     $loop = LoopFactory::create();
     $announcements = new AnnouncementsWebSocket($log);
     // Listen for the web server to make a message push.
     $broadcast = 'tcp://' . $config['broadcast']['ip'] . ':' . $config['broadcast']['port'];
     $this->info('Starting broadcast socket on ' . $broadcast);
     $context = new ZMQContext($loop);
     $broadcastSocket = $context->getSocket(ZMQ::SOCKET_PULL);
     $broadcastSocket->bind($broadcast);
     $broadcastSocket->on('message', array($announcements, 'onBroadcast'));
     // Listen for status check.
     $status = 'tcp://' . $config['status']['ip'] . ':' . $config['status']['port'];
     $this->info('Starting status socket on ' . $status);
     $statusSock = new SocketServer($loop);
     $statusSock->listen($config['status']['port'], $config['status']['ip']);
     new IoServer(new AnnouncementsServerStatus(), $statusSock);
     // Listen for WebSocket connections.
     $wsPort = $config['websocket']['port'];
     $wsIp = $config['websocket']['ip'];
     $this->info('Starting WebSocket socket on ws://' . $wsIp . ':' . $wsPort);
     $webSock = new SocketServer($loop);
     $webSock->listen($wsPort, $wsIp);
     new IoServer(new HttpServer(new WsServer($announcements)), $webSock);
     // Ping all clients each 2 min.
     $loop->addPeriodicTimer(120, function () use($announcements) {
         $announcements->ping();
     });
     $log->info('Server started');
     $loop->run();
 }
开发者ID:fencer-md,项目名称:stoticlle,代码行数:40,代码来源:AnnouncementsServer.php

示例3: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $arguments = $this->getCommandArguments($input);
     $builder = $this->getEnvironmentHelper()->getProcessBuilder($arguments);
     $command = $builder->getProcess()->getCommandLine();
     $loop = Factory::create();
     $process = new Process($command, $this->getEnvironmentHelper()->getCwd());
     $port = (int) $input->getOption('port');
     $server = $this->initializeServer($loop, $port);
     $started = false;
     $this->addEnvironmentInfo($port, $command);
     $loop->addPeriodicTimer(self::LOOP_TIMER_PERIOD, function (Timer $timer) use($output, $process, $server, &$started) {
         $clients = $server->getConnections();
         if (true === $started && false === $process->isRunning()) {
             exit($process->getExitCode());
         }
         if ($clients->count()) {
             if (!$process->isRunning()) {
                 $process->start($timer->getLoop());
                 $started = true;
                 $this->broadcastToClients($clients);
             }
             $callable = function ($output) use($clients) {
                 $this->buffer .= $output;
                 $this->broadcastToClients($clients);
             };
             $process->stdin->on('data', $callable);
             $process->stdout->on('data', $callable);
             $process->stderr->on('data', $callable);
         }
     });
     $server->bind();
     $loop->run();
 }
开发者ID:WellCommerce,项目名称:DistributionBundle,代码行数:34,代码来源:AbstractPackageCommand.php

示例4: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Make sure that websockets are enabled in the config so that the proper
     // session storage handler is used
     if (!$this->getContainer()->getParameter('bzion.features.websocket.enabled')) {
         $message = "You need to enable websockets in your config before using the push server";
         $output->writeln("<bg=red;options=bold>\n\n [ERROR] {$message}\n</>");
         return;
     }
     $loop = EventLoopFactory::create();
     $pusher = new EventPusher($loop, $output);
     $pushPort = $input->getOption('push') ?: $this->getContainer()->getParameter('bzion.features.websocket.push_port');
     $pullPort = $input->getOption('pull') ?: $this->getContainer()->getParameter('bzion.features.websocket.pull_port');
     $pullSocket = new Server($loop);
     $pullSocket->on('connection', function ($conn) use($pusher) {
         $conn->on('data', function ($data) use($pusher) {
             $pusher->onServerEvent(json_decode($data));
         });
     });
     // Bind to 127.0.0.1, so that only the server can send messages to the socket
     $pullSocket->listen($pullPort, '127.0.0.1');
     $output->writeln(" <fg=green>Running pull service on port {$pullPort}</>");
     $session = new SessionProvider($pusher, new DatabaseSessionHandler());
     $pushSocket = new Server($loop);
     $webServer = new IoServer(new WsServer($session), $pushSocket);
     // Binding to 0.0.0.0 means remotes can connect
     $pushSocket->listen($pushPort, '0.0.0.0');
     $output->writeln(" <fg=green>Running push service on port {$pushPort}</>");
     $output->writeln("\n <bg=green;options=bold>Welcome to the BZiON live notification server!</>");
     $loop->run();
 }
开发者ID:blast007,项目名称:bzion,代码行数:31,代码来源:ServerCommand.php

示例5: setUp

 public function setUp()
 {
     $this->loop = Factory::create();
     $this->dialog = $this->getMock('Clue\\React\\Zenity\\Dialog\\AbstractDialog');
     $this->dialog->expects($this->once())->method('createZen')->will($this->returnValue(new BaseZen()));
     $this->launcher = new Launcher($this->loop);
 }
开发者ID:clue,项目名称:zenity-react,代码行数:7,代码来源:FunctionalLauncherTest.php

示例6: __construct

 /**
  * @param string        $httpHost HTTP hostname clients intend to connect to. MUST match JS `new WebSocket('ws://$httpHost');`
  * @param int           $port     Port to listen on. If 80, assuming production, Flash on 843 otherwise expecting Flash to be proxied through 8843
  * @param string        $address  IP address to bind to. Default is localhost/proxy only. '0.0.0.0' for any machine.
  * @param LoopInterface $loop     Specific React\EventLoop to bind the application to. null will create one for you.
  */
 public function __construct($httpHost = 'localhost', $port = 8080, $address = '127.0.0.1', LoopInterface $loop = null, $context = array())
 {
     if (extension_loaded('xdebug')) {
         trigger_error("XDebug extension detected. Remember to disable this if performance testing or going live!", E_USER_WARNING);
     }
     if (3 !== strlen('✓')) {
         throw new \DomainException('Bad encoding, length of unicode character ✓ should be 3. Ensure charset UTF-8 and check ini val mbstring.func_autoload');
     }
     if (null === $loop) {
         $loop = LoopFactory::create();
     }
     $this->httpHost = $httpHost;
     $socket = new Reactor($loop, $context);
     $socket->listen($port, $address);
     $this->routes = new RouteCollection();
     $this->_server = new IoServer(new HttpServer(new Router(new UrlMatcher($this->routes, new RequestContext()))), $socket, $loop);
     $policy = new FlashPolicy();
     if ('*' !== $httpHost) {
         $policy->addAllowedAccess($httpHost, 80);
         $policy->addAllowedAccess($httpHost, $port);
     }
     $flashSock = new Reactor($loop);
     $this->flashServer = new IoServer($policy, $flashSock);
     if (80 == $port) {
         $flashSock->listen(843, '0.0.0.0');
     } else {
         $flashSock->listen(8843);
     }
 }
开发者ID:Rudi9719,项目名称:stein-syn,代码行数:35,代码来源:App.php

示例7: execute

 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $loop = \React\EventLoop\Factory::create();
     // Listen for the web server to make a ZeroMQ push after an ajax request
     $context = new Context($loop);
     $pull = $context->getSocket(\ZMQ::SOCKET_SUB);
     $pull->connect('tcp://127.0.0.1:5566');
     // Binding to 127.0.0.1 means the only client that can connect is itself
     $pull->subscribe('');
     $batch = 0;
     $pull->on('message', function ($msg) use(&$batch) {
         $arr = json_decode($msg);
         if ($arr->event == 'block') {
             $batch++;
         }
     });
     $period = $input->getArgument('interval');
     $loop->addPeriodicTimer($period, function () use(&$batch, $period) {
         $velocity = $batch / $period;
         echo " count: " . $batch . " - or " . $velocity . " per second " . PHP_EOL;
         $batch = 0;
     });
     $loop->run();
     return 0;
 }
开发者ID:Bit-Wasp,项目名称:node-php,代码行数:30,代码来源:BlockVelocityCommand.php

示例8: __construct

 public function __construct()
 {
     parent::__construct(function () {
         $consensus = new ConsensusFactory(Bitcoin::getEcAdapter());
         $loop = LoopFactory::create();
         $context = new ZmqContext($loop);
         $control = $context->getSocket(\ZMQ::SOCKET_SUB);
         $control->connect('tcp://127.0.0.1:5594');
         $control->subscribe('control');
         $control->on('messages', function ($msg) use($loop) {
             if ($msg[1] == 'shutdown') {
                 $loop->stop();
             }
         });
         $results = $context->getSocket(\ZMQ::SOCKET_PUSH);
         $results->connect("tcp://127.0.0.1:5593");
         $workers = $context->getSocket(\ZMQ::SOCKET_PULL);
         $workers->connect('tcp://127.0.0.1:5592');
         $workers->on('message', function ($message) use($consensus, $results) {
             $details = json_decode($message, true);
             $txid = $details['txid'];
             $flags = $details['flags'];
             $vin = $details['vin'];
             $scriptPubKey = new Script(Buffer::hex($details['scriptPubKey']));
             $tx = TransactionFactory::fromHex($details['tx']);
             $results->send(json_encode(['txid' => $txid, 'vin' => $vin, 'result' => $consensus->getConsensus(new Flags($flags))->verify($tx, $scriptPubKey, $vin)]));
         });
         $loop->run();
         exit(0);
     });
 }
开发者ID:sbwdlihao,项目名称:node-php,代码行数:31,代码来源:ScriptWorkerThread.php

示例9: start

 /**
  * start crontab and loop
  */
 public function start()
 {
     $this->logger->info("crontab start");
     $crontab = $this->createCrontab();
     $loop = Factory::create();
     // add periodic timer
     $loop->addPeriodicTimer(1, function () use($crontab) {
         $pid = pcntl_fork();
         if ($pid > 0) {
             return;
         } elseif ($pid == 0) {
             $crontab->start(time());
             exit;
         } else {
             $this->logger->error("could not fork");
             exit;
         }
     });
     // recover the sub processes
     $loop->addPeriodicTimer(60, function () {
         while (($pid = pcntl_waitpid(0, $status, WNOHANG)) > 0) {
             $message = "process exit. pid:" . $pid . ". exit code:" . $status;
             $this->logger->info($message);
         }
     });
     $loop->run();
 }
开发者ID:qianyunlai,项目名称:php_crontab,代码行数:30,代码来源:Daemon.php

示例10: eventloop_schedule_recursive

 /**
  * @test
  */
 public function eventloop_schedule_recursive()
 {
     $loop = Factory::create();
     $scheduler = new EventLoopScheduler($loop);
     $actionCalled = false;
     $count = 0;
     $action = function ($reschedule) use(&$actionCalled, &$count) {
         $actionCalled = true;
         $count++;
         if ($count < 5) {
             $reschedule();
         }
     };
     $disposable = $scheduler->scheduleRecursive($action);
     $this->assertInstanceOf('Rx\\DisposableInterface', $disposable);
     $this->assertFalse($actionCalled);
     $this->assertEquals(0, $count);
     $loop->tick();
     $this->assertEquals(1, $count);
     $loop->tick();
     $this->assertEquals(2, $count);
     $loop->tick();
     $this->assertEquals(3, $count);
     $loop->tick();
     $this->assertEquals(4, $count);
     $loop->tick();
     $this->assertEquals(5, $count);
     $loop->tick();
     $this->assertTrue($actionCalled);
     $this->assertEquals(5, $count);
 }
开发者ID:voryx,项目名称:Rx.PHP,代码行数:34,代码来源:EventLoopSchedulerTest.php

示例11: runTestProcess

 public function runTestProcess($arguments, $expectedExitCode = 0, $timeout = 5)
 {
     $command = __DIR__ . '/../../../../bin/phpunit-parallel ' . $arguments;
     $loop = Factory::create();
     $p = new Process($command);
     $p->start($loop);
     $stdout = '';
     $stderr = '';
     $timer = $loop->addTimer($timeout, function () use($arguments, $p, $stdout, $stderr) {
         $p->terminate(SIGKILL);
         $this->fail("running phpunit-parallel with '{$arguments}' did not complete in time\nstdout: {$stdout}\nstderr: {$stderr}\n");
     });
     $p->stdout->on('data', function ($data) use(&$stdout) {
         $stdout .= $data;
     });
     $p->stderr->on('data', function ($data) use(&$stderr) {
         $stderr .= $data;
     });
     $p->on('exit', function () use($timer) {
         $timer->cancel();
     });
     $loop->run();
     if ($p->getExitCode() !== $expectedExitCode) {
         $this->fail("Process exited with code {$p->getExitCode()}, expected {$expectedExitCode}\nstdout: {$stdout}\nstderr: {$stderr}\n");
     }
     return [$stdout, $stderr];
 }
开发者ID:vektah,项目名称:phpunit-parallel,代码行数:27,代码来源:EndToEndTestCase.php

示例12: testConnectWithValidPass

 public function testConnectWithValidPass()
 {
     $this->expectOutputString('endclose');
     $loop = \React\EventLoop\Factory::create();
     $conn = new Connection($loop, $this->connectOptions);
     $conn->on('end', function ($conn) {
         $this->assertInstanceOf('React\\MySQL\\Connection', $conn);
         echo 'end';
     });
     $conn->on('close', function ($conn) {
         $this->assertInstanceOf('React\\MySQL\\Connection', $conn);
         echo 'close';
     });
     $conn->connect(function ($err, $conn) use($loop) {
         $this->assertEquals(null, $err);
         $this->assertInstanceOf('React\\MySQL\\Connection', $conn);
     });
     $conn->ping(function ($err, $conn) use($loop) {
         $this->assertEquals(null, $err);
         $conn->close(function ($conn) {
             $this->assertEquals($conn::STATE_CLOSED, $conn->getState());
         });
         //$loop->stop();
     });
     $loop->run();
 }
开发者ID:xingcuntian,项目名称:reactphp-mysql,代码行数:26,代码来源:ConnectionTest.php

示例13: testWampErrorException

 function testWampErrorException()
 {
     $loop = \React\EventLoop\Factory::create();
     $router = new \Thruway\Peer\Router($loop);
     //$router->addTransportProvider(new \Thruway\Transport\RawSocketTransportProvider());
     $client = new \Thruway\Peer\Client("realm1", $loop);
     $client->setAttemptRetry(false);
     $client->on('open', function (\Thruway\ClientSession $session) use($router) {
         $session->register('procedure_with_exception', function ($args) {
             throw new \Thruway\Exception\WampErrorException("error.from.exception", $args, (object) ["theKw" => "great"], (object) ["more_details" => "some_more_details"]);
         })->then(function () use($session, $router) {
             $session->call('procedure_with_exception', ['one', 'two'])->then(function ($args) use($router) {
                 $this->fail('Call with wamp exception should not have succeeded.');
                 $router->stop();
             }, function ($err) use($router) {
                 /** @var \Thruway\Message\ErrorMessage $err */
                 $this->assertInstanceOf('Thruway\\Message\\ErrorMessage', $err);
                 $this->assertTrue(is_array($err->getArguments()));
                 $this->assertEquals(2, count($err->getArguments()));
                 $this->assertEquals("one", $err->getArguments()[0]);
                 $this->assertEquals("two", $err->getArguments()[1]);
                 $this->assertInstanceOf('stdClass', $err->getArgumentsKw());
                 $this->assertObjectHasAttribute('theKw', $err->getArgumentsKw());
                 $this->assertEquals('great', $err->getArgumentsKw()->theKw);
                 $this->assertObjectHasAttribute('more_details', $err->getDetails());
                 $this->assertEquals('some_more_details', $err->getDetails()->more_details);
                 $this->assertEquals('error.from.exception', $err->getErrorURI());
                 $router->stop();
             });
         });
     });
     //$client->addTransportProvider(new \Thruway\Transport\RawSocketClientTransportProvider());
     $router->addInternalClient($client);
     $router->start();
 }
开发者ID:binaek89,项目名称:Thruway,代码行数:35,代码来源:WampErrorExceptionTest.php

示例14: getLoop

 /**
  * @return LoopInterface
  */
 public function getLoop()
 {
     if (is_null(static::$loop)) {
         static::setLoop(Factory::create());
     }
     return static::$loop;
 }
开发者ID:krinfreschi,项目名称:async-streams,代码行数:10,代码来源:AsyncStreamWrapper.php

示例15: setupServer

 /**
  * Sets up loop and server manually to allow periodic timer calls.
  */
 private function setupServer()
 {
     $this->setupApp();
     /** @var $loop \React\EventLoop\LoopInterface */
     $this->loop = \React\EventLoop\Factory::create();
     // Enable ZMQ Listener.
     // Requires , "react/zmq" package.
     $zmq = $this->getContainer()->getParameter('jdare_clank.zmq_configuration');
     if ($zmq['enabled']) {
         if (!class_exists('\\ZMQContext')) {
             throw new \Exception("Could not find ZMQContext, did you install the zmq bindings for PHP?");
         }
         // Listen for the web server to make a ZeroMQ push after an ajax request
         $context = new \React\ZMQ\Context($this->loop);
         $pull = $context->getSocket(\ZMQ::SOCKET_PULL);
         $bind = "tcp://127.0.0.1:{$zmq['port']}";
         echo "\nListening to ZMQ messages on {$bind}\n";
         $pull->bind($bind);
         // Binding to 127.0.0.1 means the only client that can connect is itself
         $pull->on('message', array($this->getContainer()->get("jdare_clank.clank_app"), 'onZMQMessage'));
     }
     $this->socket = new \React\Socket\Server($this->loop);
     if ($this->host) {
         $this->socket->listen($this->port, $this->host);
     } else {
         $this->socket->listen($this->port);
     }
     $this->setupPeriodicServices();
     $this->server = new \Ratchet\Server\IoServer($this->app, $this->socket, $this->loop);
 }
开发者ID:HenderOrlando,项目名称:ClankBundle,代码行数:33,代码来源:WebSocketServerType.php


注:本文中的React\EventLoop\Factory类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。