/** * 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; }
/** * 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(); }
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(); }
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(); }
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); }
/** * @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); } }
/** * @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; }
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); }); }
/** * 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(); }
/** * @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); }
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]; }
public function __construct($config) { $loop = eventLoop::create(); $this->loop = $loop; $this->serv = new server($loop); $this->config = $config; }
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(); }
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(); }
/** * @return LoopInterface */ public function getLoop() { if (is_null(static::$loop)) { static::setLoop(Factory::create()); } return static::$loop; }
/** * 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); }
/** * @param $channel * @param string $message * @return DeferredPromise */ public function call($channel, $message) { $loop = LoopFactory::create(); $factory = new StompFactory($loop); $client = $factory->createClient(); $deferred = new Deferred(); $timer = $loop->addTimer(2, function () use($deferred, $client) { $client->disconnect(); $deferred->reject(new RpcTimeIsOutException()); }); $client->connect()->then(function (StompClient $client) use($message, $channel, $loop, $deferred, $timer) { $rpcReceiver = function (Frame $frame) use($deferred, $timer, $client) { $timer->cancel(); $client->disconnect(); try { $deferred->resolve($frame); } catch (\Exception $e) { $deferred->reject($e); } }; $client->sendToTemp($channel, $message, [], $rpcReceiver); }, function () use($deferred, $client) { $client->disconnect(); $deferred->reject(new \RuntimeException('Error start rpc connection')); }); $loop->run(); return $deferred->promise(); }
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void Script exit code */ protected function execute(InputInterface $input, OutputInterface $output) { $brainName = $input->getArgument('brain'); $host = $input->getArgument('server'); $brain = $this->brainFactory->build($brainName); $responseInterpreter = new \Connect4\Client\ResponseInterpreter(); $client = new \Connect4\Client\Client($brain); $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($host, 1337)->then(function (\React\Stream\Stream $stream) use($brain, $responseInterpreter, $client) { $stream->write($brain->getName()); $stream->on('data', function ($data) use($stream, $client, $responseInterpreter) { if (!$data) { die('CONNECTION TERMINATED'); } $response = $responseInterpreter->buildResponse($data); $move = $client->handle($response); if ($move) { $stream->write($move->getColumn()->getValue()); } }); }); $loop->run(); }
protected function execute(InputInterface $input, OutputInterface $output) { $loop = \React\EventLoop\Factory::create(); $pusher = $this->getContainer()->get('websocket'); $worldService = $this->getContainer()->get('worldevent'); $dataChannel = $this->getContainer()->get('datachannel'); // Циклическое событие $loop->addPeriodicTimer(120, function () use($pusher, $worldService, $dataChannel) { // Юзеры онлайн $onlineChars = $dataChannel->clients; // Вызов сообщения о погоде $worldEventWeather = $worldService->weather($onlineChars); if ($worldEventWeather) { $charsOutside = $worldEventWeather["chars"]; $weather = $worldEventWeather["weather"]; $worldEvent = array("worldweather" => $weather); // Отправка всем сводки о погоде $pusher->sendToList($charsOutside, $worldEvent); } }); // Запуск вебсокет сервера $webSock = new \React\Socket\Server($loop); $webSock->listen(6661, '0.0.0.0'); // Привязка к 0.0.0.0 позволяет коннектиться удаленно new \Ratchet\Server\IoServer(new \Ratchet\Http\HttpServer(new \Ratchet\WebSocket\WsServer(new \Ratchet\Wamp\WampServer($pusher))), $webSock); $loop->run(); }
/** * Init the API components */ public function init() { $this->loop = Factory::create(); // Catch signals $this->loop->addPeriodicTimer(1, function () { pcntl_signal_dispatch(); }); // Heartbeat, 2 minutes officially, here 5 $this->loop->addPeriodicTimer(300, [$this, 'doHeartbeats']); // Clients logging if (true === ConfigurationLoader::get('client.async.enabled')) { $this->loop->addPeriodicTimer(0.5, function () { LoggerFactory::subscribe(); }); } // Init router $this->router = new Router(); $this->router->init(); // Init redis $this->redis = new Client(sprintf('tcp://%s:%d', ConfigurationLoader::get('client.async.redis.host'), ConfigurationLoader::get('client.async.redis.port'))); // Async processes if (true === ConfigurationLoader::get('client.async.enabled')) { $this->clean(true); $this->catchSignals(); } else { $this->logger->warning('You use the slow mode (synchronous), you can use the fast mode (asynchronous) by setting the configuration "client.async.enabled" to "true"'); } }
public function assertConnection(array $options, $message = null) { $settings = array_merge(["ip" => "0.0.0.0", "port" => 0, "startServer" => false, "match" => true], $options); // optionally starting server if ($settings["startServer"]) { $serverLoop = EventLoopFactory::create(); $server = new SocketServer($serverLoop); $server->listen($settings["port"]); } // client setup $clientLoop = EventLoopFactory::create(); $dnsResolverFactory = new DnsResolverFactory(); $dns = $dnsResolverFactory->createCached("8.8.8.8", $clientLoop); // dunno why dns is required for this shit $connector = new SocketConnector($clientLoop, $dns); $promise = $connector->create($settings["ip"], $settings["port"])->then(function (SocketStream $stream) { $stream->close(); return true; }, function (SocketConnectionException $e) { return false; }); $clientLoop->run(); // catching the output $out = null; $promise->done(function ($v) use(&$out) { $out = $v; }); // optionally cleaning up the server if ($settings["startServer"]) { $server->shutdown(); } $this->assertEquals($out, $settings["match"], $message); }
public function execute(InputInterface $input, OutputInterface $output) { /** * @var \Symfony\Component\Console\Helper\FormatterHelper */ $formatter = $this->getHelper('formatter'); $output->writeln($formatter->formatSection('IO', 'Start development server')); $bridgeName = $input->getOption('bridge'); switch (strtolower($bridgeName)) { case 'phalcony': $bridge = new Phalcony(); break; case 'hello': default: $bridge = new SimpleBridge(); break; } $bridge->on('error', function (Exception $e) use(&$formatter, $output) { $output->writeln($formatter->formatBlock(array('[App]', $e->getMessage(), 'in the ' . $e->getFile() . ' file on ' . $e->getLine() . ' line'), 'error')); }); $listen = $input->getOption('listen'); $port = $input->getOption('port'); $count = $input->getOption('count'); for ($i = 0; $i < $count; $i++) { $this->newWorker($output, $formatter, $listen, $port + $i, clone $bridge); } $loop = Factory::create(); $loop->addPeriodicTimer(1, function () use(&$output) { $output->writeln('Tick tak, bitch <3'); }); $loop->run(); }
/** * Builds internal request handling objects. * * @return $this */ public function build() { if ($this->cache) { $loader = new ClassLoader(); if ($this->apc) { $apcLoader = new ApcClassLoader(sha1('ReactServer'), $loader); $loader->unregister(); $apcLoader->register(true); } } require_once $this->root_dir . '/AppKernel.php'; define('KERNEL_ROOT', $this->root_dir); $kernel = new ReactKernel($this->env, $this->env === 'dev' ? true : false); $this->loop = Factory::create(); // TODO make config for this part if (class_exists('\\Doctrine\\DBAL\\Driver\\PingableConnection')) { $this->loop->addPeriodicTimer(15, function () use($kernel) { foreach ($kernel->getContainer()->get('doctrine')->getConnections() as $connection) { if ($connection instanceof \Doctrine\DBAL\Driver\PingableConnection) { $connection->ping(); } } }); } $this->socket = new SocketServer($this->loop); $http = new HttpServer($this->socket, $this->loop); $http->on('request', $this->handleRequest($kernel)); return $this; }
public function __construct(LoggerInterface $logger) { $this->loop = EventLoop::create(); $this->socket = new ReactSocket($this->loop); $this->http = new ReactServer($this->socket); $this->logger = $logger; }
/** * @param \Ratchet\MessageComponentInterface $component The application that I/O will call when events are received * @param int $port The port to server sockets on * @param string $address The address to receive sockets on (0.0.0.0 means receive connections from any) * @return IoServer */ public static function factory(MessageComponentInterface $component, $port = 80, $address = '0.0.0.0') { $loop = LoopFactory::create(); $socket = new Reactor($loop); $socket->listen($port, $address); return new static($component, $socket, $loop); }
public function createService(ServiceLocatorInterface $controllerManager) { $serviceLocator = $controllerManager->getServiceLocator(); $loop = EventLoopFactory::create(); $config = $serviceLocator->get('Config'); return new RunRealtimeServer($loop, new SocketServer($loop), $config['t4web-queue']['queues']); }
/** * {@inheritdoc} */ protected function doSendInternalRequest(InternalRequestInterface $internalRequest) { $loop = EventLoopFactory::create(); $dnsResolverFactory = new DnsResolverFactory(); $httpClientFactory = new HttpClientFactory(); $error = null; $response = null; $body = null; $request = $httpClientFactory->create($loop, $dnsResolverFactory->createCached('8.8.8.8', $loop))->request($internalRequest->getMethod(), $url = (string) $internalRequest->getUrl(), $this->prepareHeaders($internalRequest, true, true, true)); $request->on('error', function (\Exception $onError) use(&$error) { $error = $onError; }); $request->on('response', function (Response $onResponse) use(&$response, &$body) { $onResponse->on('data', function ($data) use(&$body) { $body .= $data; }); $response = $onResponse; }); $request->end($this->prepareBody($internalRequest)); $loop->run(); if ($error !== null) { throw HttpAdapterException::cannotFetchUrl($url, $this->getName(), $error->getMessage()); } return $this->getConfiguration()->getMessageFactory()->createResponse((int) $response->getCode(), $response->getReasonPhrase(), $response->getVersion(), $response->getHeaders(), BodyNormalizer::normalize($body, $internalRequest->getMethod())); }
public function start($count = 1) { $loop = Factory::create(); $server = stream_socket_server($this->config->getConnectionString()); if ($server === false) { throw new \RuntimeException("create socket server failed"); } $blocking = stream_set_blocking($server, 0); if ($blocking === false) { throw new \RuntimeException("stream_set_blocking failed"); } $loop->addReadStream($server, function ($server) use($loop) { $dispatcher = $this->config->getDispatcher(); if ($dispatcher !== null && !$dispatcher->acquire($server, $loop)) { return; } $conn = stream_socket_accept($server); $dispatcher->release($server, $loop); $loop->addReadStream($conn, function ($conn) use($loop) { call_user_func(array($this->handler, 'handle'), $conn, $loop); }); }); $master = new Master($loop, $count); $master->start(); }
public function __construct($config = []) { self::configure($config); $config = \SciActive\RequirePHP::_('NymphPubSubConfig'); $this->loop = \React\EventLoop\Factory::create(); // Create a logger which writes everything to the STDOUT $this->logger = new \Zend\Log\Logger(); $this->writer = new \Zend\Log\Writer\Stream("php://output"); $this->logger->addWriter($this->writer); // Create a WebSocket server using SSL try { $this->logger->notice("Nymph-PubSub server starting on {$config['host']}:{$config['port']}."); } catch (\Exception $e) { if (strpos($e->getMessage(), 'date.timezone')) { echo "It looks like you haven't set a default timezone. In order to avoid constant complaints from Zend's logger, I'm just going to kill myself now.\n\n"; echo $e->getMessage() . "\n"; exit; } throw $e; } $this->server = new WebSocketServer("tcp://{$config['host']}:{$config['port']}", $this->loop, $this->logger); // Create a router which transfers all /chat connections to the MessageHandler class $this->router = new \Devristo\Phpws\Server\UriHandler\ClientRouter($this->server, $this->logger); // route / url $this->router->addRoute('#^/#i', new MessageHandler($this->logger)); // route unmatched urls $this->router->addRoute('#^(.*)$#i', new MessageHandlerForUnroutedUrls($this->logger)); // Bind the server $this->server->bind(); }
/** * Returns the event loop dependency, initializing it if needed. * * @return \React\EventLoop\LoopInterface */ public function getLoop() { if (!$this->loop) { $this->loop = \React\EventLoop\Factory::create(); } return $this->loop; }