/**
  * Create a new file driven handler instance.
  *
  * @param \Illuminate\Filesystem\Filesystem $files
  * @param React\EventLoop\LoopInterface $loop
  * @param string $path
  * 
  * @return void
  */
 public function __construct(Factory $factory, LoopInterface $loop, Server $server, $lifetime)
 {
     $this->factory = $factory;
     $this->lifetime = $lifetime;
     $this->server = $server;
     $this->loop = $loop;
     // PING redis connection every 5 minutes
     // and try to reconnect on connection error
     $this->timer = $loop->addPeriodicTimer(60 * 1, function () use($server) {
         $this->promise->then(function ($client) use($server) {
             $client->PING()->then(function ($pong) use($server) {
                 $server->log('Redis server responded ping with: %s', [$pong]);
                 return $pong == 'PONG';
             }, function ($e) {
                 return $this->reconnectByError($e);
             });
         });
     });
     // server statistics for redis connection
     $this->loop->addPeriodicTimer(60 * 30, function () {
         $this->server->log('Server statistics to the last 30 minutes.');
         $this->server->log('Best time of %fs, poor time of %fs and a average of %f seconds for total %d requests.', array_values($this->statistics));
         $this->statistics = array('best' => 0, 'poor' => 0, 'avg' => 0, 'total' => 0);
     });
 }
Пример #2
0
 /**
  * Start the HTTP Server
  */
 public function start()
 {
     $this->httpServer->on('request', [$this, 'handleRequest']);
     $this->logger->info("Server is listening at " . $this->configuration['listen']['host'] . ":" . $this->configuration['listen']['port']);
     $this->socketServer->listen($this->configuration['listen']['port'], $this->configuration['listen']['host']);
     $this->eventLoop->run();
 }
Пример #3
0
 public function __construct(TransportInterface $carrierProtocol, LoopInterface $loop, LoggerInterface $logger)
 {
     $that = $this;
     $this->logger = $logger;
     $this->loop = $loop;
     $this->carrierProtocol = $carrierProtocol;
     $this->actionEmitter = new EventEmitter();
     $deferreds =& $this->deferred;
     $timers =& $this->timers;
     $carrierProtocol->on("message", function (MessageInterface $message) use(&$deferreds, &$timers, &$loop, $that, $logger) {
         $string = $message->getData();
         try {
             $jsonMessage = RemoteEventMessage::fromJson($string);
             $tag = $jsonMessage->getTag();
             if (array_key_exists($tag, $deferreds)) {
                 $deferred = $deferreds[$tag];
                 unset($deferreds[$tag]);
                 if (array_key_exists($tag, $timers)) {
                     $loop->cancelTimer($timers[$tag]);
                     unset($timers[$tag]);
                 }
                 $deferred->resolve($jsonMessage);
             } else {
                 $that->remoteEvent()->emit($jsonMessage->getEvent(), array($jsonMessage));
             }
             $that->emit("message", array($jsonMessage));
         } catch (\Exception $e) {
             $logger->err("Exception while parsing JsonMessage: " . $e->getMessage());
         }
     });
 }
Пример #4
0
 /**
  * Adds timer to Loop queue
  *
  * @param float $interval
  * @return TimerInterface
  */
 public function start($interval = self::DEFAULT_INTERVAL)
 {
     if ($this->timer) {
         $this->stop();
     }
     return $this->timer = $this->loop->addPeriodicTimer($interval, $this);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->client->getUsers()->then(function ($users) use($output) {
         $this->importUsers($users, $output);
     });
     $this->loop->run();
 }
Пример #6
0
 /**
  * Starts downloader in daemon mode, awaiting for future tasks
  * @todo Locks and signal processing
  *
  * @param EventLoop\LoopInterface $loop A loop, worker is run on
  */
 public function runDaemon(EventLoop\LoopInterface $loop)
 {
     $loop->addPeriodicTimer($this->tick, function ($timer) use($loop) {
         $this->run($loop, $this->limit);
     });
     $loop->run();
 }
 /**
  * Listen for exit command and terminate
  * the event loop
  *
  * @param string $data
  * @return void
  */
 public function write($data)
 {
     if (trim($data) === self::EXIT_CMD) {
         $this->loop->stop();
         $this->close();
     }
 }
Пример #8
0
 public function getStatus(callable $callback)
 {
     $this->request('status', [], function ($result) use($callback) {
         $callback(json_decode($result, true));
     });
     $this->loop->run();
 }
Пример #9
0
 function it_adds_a_read_stream($socket, ChannelInterface $channel, ConnectionInterface $connection, LoopInterface $loop)
 {
     $channel->getConnection()->willReturn($connection);
     $connection->getSocket()->willReturn($socket);
     $loop->addReadStream($socket, [$this, 'wait'])->shouldBeCalled();
     $this->beConstructedWith($channel, $loop);
 }
Пример #10
0
 public function __construct(LoopInterface $loop, EventEmitter $emit, \SplObjectStorage $clients, RoundProcessor $roundProcessor, EngineHelper $helper, $time = 60, $debug = false)
 {
     $this->debug = $debug;
     $this->helper = $helper;
     $this->emit = $emit;
     $this->loop = $loop;
     $this->roundTimer = new RoundTimer($loop, $emit);
     $this->roundNumber = 0;
     $this->clients = $clients;
     $this->disconnected = new \SplObjectStorage();
     $this->time = $time;
     $that = $this;
     $this->say = new Say($this->clients);
     $this->roundProcessor = $roundProcessor;
     $players = new Say($this->clients);
     // Setup listeners on the roundTimer object.
     $emit->on('GAME.COUNTDOWN', function () use($that) {
         if ($this->playerCount !== $this->clients->count()) {
             $this->playerCount = $this->clients->count();
             $this->say->to($this->clients)->that(Say::TICK, ["players" => $this->playerCount]);
         }
     });
     // Setup listeners on the roundTimer object.
     $emit->on('GAME.COUNTDOWN_END', function () use($that, $loop, $emit) {
         $this->say->to($this->clients)->that(Say::GAME_STARTING, ["players" => $this->clients->count()]);
         $this->setGameStarted(true);
         $loop->addTimer(3, function () use($loop, $emit) {
             $this->startRound($loop, $emit);
         });
     });
     $this->roundTimer->startCountDown($this->time);
 }
Пример #11
0
 /**
  *
  */
 public function close()
 {
     $this->loop->removeReadStream($this->socket);
     if (is_resource($this->socket)) {
         fclose($this->socket);
     }
     $this->notifyCompleted();
 }
Пример #12
0
 /**
  * Create a new event pusher handler
  */
 public function __construct(LoopInterface $loop, OutputInterface $output = null)
 {
     $this->loop = $loop;
     $this->output = $output;
     $this->clients = new \SplObjectStorage();
     $this->subscriber = \Service::getContainer()->get('kernel.subscriber.bzion_subscriber');
     // Ping timer
     $loop->addPeriodicTimer(self::KEEP_ALIVE, array($this, 'ping'));
 }
Пример #13
0
 /**
  * Run the application by entering the event loop
  * @throws \RuntimeException If a loop was not previously specified
  */
 public function run()
 {
     if (null === $this->loop) {
         throw new \RuntimeException("A React Loop was not provided during instantiation");
     }
     // @codeCoverageIgnoreStart
     $this->loop->run();
     // @codeCoverageIgnoreEnd
 }
Пример #14
0
 /**
  * @param array $options
  * @param array $arguments
  * @return mixed
  */
 public function run(array $options, array $arguments)
 {
     $port = isset($arguments[0]) ? $arguments[0] : "8001";
     $host = isset($arguments[1]) ? $arguments[1] : "0.0.0.0";
     /** @var \Castle23\Http\Server $server */
     $server = $this->container->getInstanceOf(Server::class);
     $this->socket->listen($port, $host);
     $this->loop->run();
 }
Пример #15
0
 public function close()
 {
     if ($this->closed) {
         return;
     }
     $this->loop->cancelTimer($this->timer);
     unset($this->queue);
     $this->closed = true;
 }
 public function promiseAction(Request $request)
 {
     $secs = intval($request->attributes->get("secs"));
     $deferred = new Deferred();
     $this->loop->addTimer($secs, function () use($secs, $deferred) {
         $deferred->resolve(Response::create("{$secs} seconds later...\n"));
     });
     return $deferred->promise();
 }
Пример #17
0
 public function __construct(LoopInterface $loop)
 {
     $bspcProcess = proc_open('pactl subscribe', [['pipe', 'r'], ['pipe', 'w']], $pipes);
     $bspcStdout = new Stream($pipes[1], $loop);
     $bspcStdout->on('data', [$this, 'onUpdate']);
     $loop->addTimer(0, function () {
         $this->queryData();
     });
 }
Пример #18
0
 public function __construct(LoopInterface $loop, FrameBuffer $frameBuffer, ContainerInterface $container)
 {
     $this->loop = $loop;
     $this->frameBuffer = $frameBuffer;
     $this->container = $container;
     $this->connections = new \SplObjectStorage();
     $fps = (double) $container->get('server.fps');
     $this->update_timer = $this->loop->addPeriodicTimer(1.0 / $fps, [$this, 'onFrameUpdate']);
     $this->switchToGameLoop($container->get(TestImageScreen::class));
 }
Пример #19
0
 public function testLoopStartStop()
 {
     $timer = $this->getMock('React\\EventLoop\\Timer\\TimerInterface');
     $this->loop->expects($this->exactly(2))->method('addPeriodicTimer')->with(0.1, $this->isType('callable'))->willReturn($timer);
     $timer->expects($this->once())->method('isActive')->willReturn(true);
     $timer->expects($this->once())->method('cancel');
     $pcntl = new PCNTL($this->loop);
     $timer = $pcntl->start();
     $this->assertInstanceOf('\\React\\EventLoop\\Timer\\TimerInterface', $timer);
 }
Пример #20
0
 /**
  * NewEventLoopScheduler constructor.
  * @param callable|LoopInterface $timerCallableOrLoop
  */
 public function __construct($timerCallableOrLoop)
 {
     // passing a loop directly into the scheduler will be deprecated in the next major release
     $this->timerCallable = $timerCallableOrLoop instanceof LoopInterface ? function ($ms, $callable) use($timerCallableOrLoop) {
         $timerCallableOrLoop->addTimer($ms / 1000, $callable);
     } : $timerCallableOrLoop;
     parent::__construct($this->now(), function ($a, $b) {
         return $a - $b;
     });
 }
Пример #21
0
 public function start()
 {
     $this->loop = \WyriHaximus\Ratchet\loopResolver();
     $router = new Router($this->loop);
     $router->addInternalClient(new InternalClient('first', $this->loop));
     $router->addTransportProvider(new RatchetTransportProvider(Configure::read('WyriHaximus.Ratchet.Connection.Websocket.address'), Configure::read('WyriHaximus.Ratchet.Connection.Websocket.port')));
     //$router->getRealmManager()->setDefaultAuthorizationManager(new AllPermissiveAuthorizationManager());
     EventManager::instance()->dispatch(WebsocketStartEvent::create($this->loop));
     $router->start(false);
     $this->loop->run();
 }
Пример #22
0
 protected function processQueue()
 {
     $this->loop->futureTick(function () {
         if ($this->callQueue->isEmpty()) {
             return;
         }
         $message = $this->callQueue->dequeue();
         $data = ['function' => $message->getFunction(), 'args' => $message->getArgs(), 'errorResultCode' => $message->getErrorResultCode()];
         $message->getDeferred()->resolve($data);
     });
 }
Пример #23
0
 /**
  * {@inheritdoc}
  */
 public function stop()
 {
     if (null !== $this->loop) {
         $this->loop->stop();
         $this->httpServer->removeAllListeners();
         $this->httpServer = null;
         $this->socketServer->shutdown();
         $this->socketServer = null;
         $this->loop = null;
     }
 }
Пример #24
0
 /**
  * Starts the websocket server
  *
  * @return void
  */
 public function start()
 {
     $this->__loop = LoopFactory::create();
     if ($this->__loop instanceof \React\EventLoop\StreamSelectLoop) {
         $this->out('<warning>Your configuration doesn\'t seem to support \'ext-libevent\'. It is highly reccomended that you install and configure it as it provides significant performance gains over stream select!</warning>');
     }
     $socket = new Reactor($this->__loop);
     $socket->listen(Configure::read('Ratchet.Connection.websocket.port'), Configure::read('Ratchet.Connection.websocket.address'));
     $this->__ioServer = new IoServer(new HttpServer(new WsServer(new SessionProvider(new WampServer(new CakeWampAppServer($this, $this->__loop, CakeEventManager::instance(), $this->params['verbose'])), new CakeWampSessionHandler(), [], new PhpSerializeHandler()))), $socket, $this->__loop);
     $this->__loop->run();
 }
Пример #25
0
 public function start()
 {
     $this->bindSignals();
     //master process shutdown request handler
     $this->loop->addPeriodicTimer(1, function () {
         pcntl_signal_dispatch();
     });
     foreach ($this->daemons as $daemon) {
         $this->daemons[$daemon] = $this->newInstance($daemon);
     }
 }
 /**
  * @param string $name
  */
 public function cancelPeriodicTimer($tidOrname)
 {
     if (!isset($this->registry[$tidOrname])) {
         $tid = $this->getTid($tidOrname);
     } else {
         $tid = $tidOrname;
     }
     $timer = $this->registry[$tid];
     $this->loop->cancelTimer($timer);
     unset($this->registry[$tid]);
 }
Пример #27
0
 /**
  * Create a queue with fanout exchange.
  *
  * @param string $exchange
  * @param string $queue
  *
  * @return PromiseInterface
  */
 public function fanout($exchange, $queue)
 {
     if (!isset($this->queues[$queue])) {
         $this->queues[$queue] = $this->connect()->then(function (Channel $channel) use($exchange, $queue) {
             return \React\Promise\all([$channel, $channel->queueDeclare($queue), $channel->exchangeDeclare($exchange, 'fanout'), $channel->queueBind($queue, $exchange)]);
         }, function (Exception $exception) {
             $this->loop->stop();
             throw new AsyncMessagingException(sprintf('Could not create channel and exchange: %s on line %s in file %s', $exception->getMessage(), $exception->getLine(), $exception->getFile()), 0, $exception);
         });
     }
     return $this->queues[$queue];
 }
Пример #28
0
 /**
  * Runs the message server on the given port.
  *
  * @param string  $consumer Command to execute when a message arrives
  * @param integer $port     Port to run the server on
  *
  * @return void
  */
 public function run($consumer, $port, $callback = null)
 {
     // @codeCoverageIgnoreStart
     $this->socket->on('connection', function (ConnectionInterface $conn) use($consumer, $callback) {
         $conn->on('data', function ($data) use($conn, $consumer, $callback) {
             $this->handleData(trim($data), $consumer, $conn, $callback);
         });
     });
     // @codeCoverageIgnoreEnd
     $this->socket->listen($port);
     $this->loop->run();
 }
Пример #29
0
function resolve($time, LoopInterface $loop)
{
    return new Promise(function ($resolve) use($loop, $time, &$timer) {
        // resolve the promise when the timer fires in $time seconds
        $timer = $loop->addTimer($time, function () use($time, $resolve) {
            $resolve($time);
        });
    }, function ($resolveUnused, $reject) use(&$timer, $loop) {
        // cancelling this promise will cancel the timer and reject
        $loop->cancelTimer($timer);
        $reject(new \RuntimeException('Timer cancelled'));
    });
}
Пример #30
0
 /**
  * Start the websocket server
  */
 public function start()
 {
     $this->__loop = Factory::create();
     $pusher = new CakeWampAppServer();
     $context = new Context($this->__loop);
     $pull = $context->getSocket(ZMQ::SOCKET_PULL);
     $pull->bind("tcp://" . Configure::read('CakeRatchet.ZMQServer.host') . ":" . Configure::read('CakeRatchet.ZMQServer.port'));
     $pull->on('message', array($pusher, 'onBlogEntry'));
     $webSock = new Server($this->__loop);
     $webSock->listen(Configure::read('CakeRatchet.Server.port'), Configure::read('CakeRatchet.Server.host'));
     $this->__ioServer = new IoServer(new HttpServer(new WsServer(new WampServer($pusher))), $webSock);
     $this->__loop->run();
 }