コード例 #1
0
ファイル: ProcessSlave.php プロジェクト: php-pm/php-pm
 /**
  * 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();
 }
コード例 #2
0
ファイル: ConnectionTest.php プロジェクト: ramiyer/react
 /**
  * @covers React\Socket\Connection::write
  */
 public function testWriteError()
 {
     $socket = "Silly developer, you can't write to to a string!";
     $loop = $this->createWriteableLoopMock();
     $conn = new Connection($socket, $loop);
     $conn->on('error', $this->expectCallableOnce());
     $conn->write('Attempting to write to a string');
 }
コード例 #3
0
ファイル: client.php プロジェクト: greevex/react-easy-server
 /**
  * Initialize new client object wrapped by specified protocol
  *
  * @param resource $socket Stream socket resource of connection
  * @param React\EventLoop\LoopInterface $loop
  * @param protocolInterface             $protocol
  */
 public function __construct($socket, React\EventLoop\LoopInterface $loop, protocolInterface $protocol)
 {
     $this->clientConnection = new React\Socket\Connection($socket, $loop);
     $this->loop = $loop;
     $this->protocol = $protocol;
     $this->id = stream_socket_get_name($this->clientConnection->stream, false) . '<->' . stream_socket_get_name($this->clientConnection->stream, true);
     $this->protocol->on('command', function ($command) {
         $this->emit('command', [$command, $this]);
     });
     $this->clientConnection->on('data', [$this->protocol, 'onData']);
     $this->clientConnection->on('error', function ($error) {
         $this->emit('error', [$error, $this]);
     });
     $this->clientConnection->on('close', function () {
         $this->emit('close', [$this]);
     });
 }
コード例 #4
0
ファイル: Controller.php プロジェクト: phxlol/lol-php-api
 /**
  * Apply revoked client connection listeners
  */
 protected function applyListeners()
 {
     foreach ($this->listeners as $listenerName => $listeners) {
         foreach ($listeners as $listener) {
             $this->conn->on('api-' . $listenerName, $listener);
         }
     }
     $this->listeners = [];
 }
コード例 #5
0
ファイル: ProcessSlave.php プロジェクト: atiarda/php-pm
 public function connectToMaster()
 {
     $this->loop = \React\EventLoop\Factory::create();
     $this->client = stream_socket_client('tcp://127.0.0.1:5500');
     $this->connection = new \React\Socket\Connection($this->client, $this->loop);
     $this->connection->on('close', \Closure::bind(function () {
         $this->shutdown();
     }, $this));
     $socket = new \React\Socket\Server($this->loop);
     $http = new \React\Http\Server($socket);
     $http->on('request', array($this, 'onRequest'));
     $port = 5501;
     while ($port < 5600) {
         try {
             $socket->listen($port);
             break;
         } catch (\React\Socket\ConnectionException $e) {
             $port++;
         }
     }
     $this->connection->write(json_encode(array('cmd' => 'register', 'pid' => getmypid(), 'port' => $port)));
 }
コード例 #6
0
 /**
  * Binds data-listener to $conn and waits for incoming commands.
  *
  * @param Connection $conn
  */
 protected function bindProcessMessage(Connection $conn)
 {
     $buffer = '';
     $conn->on('data', \Closure::bind(function ($data) use($conn, &$buffer) {
         $buffer .= $data;
         if (substr($buffer, -strlen(PHP_EOL)) === PHP_EOL) {
             foreach (explode(PHP_EOL, $buffer) as $message) {
                 if ($message) {
                     $this->processMessage($message, $conn);
                 }
             }
             $buffer = '';
         }
     }, $this));
 }
コード例 #7
0
ファイル: ProcessSlave.php プロジェクト: marcj/php-pm
 /**
  * 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();
 }
コード例 #8
0
ファイル: ProcessManager.php プロジェクト: ravismula/php-pm
 public function onSlaveConnection(\React\Socket\Connection $conn)
 {
     $conn->on('data', \Closure::bind(function ($data) use($conn) {
         $this->onData($data, $conn);
     }, $this));
     $conn->on('close', \Closure::bind(function () use($conn) {
         foreach ($this->slaves as $idx => $slave) {
             if ($slave['connection'] === $conn) {
                 unset($this->slaves[$idx]);
                 $this->checkSlaves();
             }
         }
     }, $this));
 }
コード例 #9
0
ファイル: ProcessManager.php プロジェクト: marcj/php-pm
 /**
  * Handles incoming connections from $this->port. Basically redirects to a slave.
  *
  * @param Connection $incoming incoming connection from react
  */
 public function onWeb(Connection $incoming)
 {
     // preload sent data from $incoming to $buffer, otherwise it would be lost,
     // since getNextSlave is async.
     $redirect = null;
     $buffer = '';
     $incoming->on('data', function ($data) use(&$redirect, &$buffer) {
         if (!$redirect) {
             $buffer .= $data;
         }
     });
     $this->getNextSlave(function ($id) use($incoming, &$buffer, &$redirect) {
         $slave =& $this->slaves[$id];
         $slave['busy'] = true;
         $slave['connections']++;
         $this->tcpConnector->create('127.0.0.1', $slave['port'])->then(function (\React\Stream\Stream $stream) use(&$buffer, $redirect, $incoming, &$slave) {
             $stream->write($buffer);
             $stream->on('close', function () use($incoming, &$slave) {
                 $slave['busy'] = false;
                 $slave['connections']--;
                 $slave['requests']++;
                 $incoming->end();
                 if ($slave['requests'] > $this->maxRequests) {
                     $info['ready'] = false;
                     $slave['connection']->close();
                 }
                 if ($slave['closeWhenFree']) {
                     $slave['connection']->close();
                 }
             });
             $stream->on('data', function ($data) use($incoming) {
                 $incoming->write($data);
             });
             $incoming->on('data', function ($data) use($stream) {
                 $stream->write($data);
             });
             $incoming->on('close', function () use($stream) {
                 $stream->close();
             });
         });
     });
 }
コード例 #10
0
ファイル: ProcessManager.php プロジェクト: php-pm/php-pm
 /**
  * A slave sent a `status` command.
  *
  * @param array      $data
  * @param Connection $conn
  */
 protected function commandStatus(array $data, Connection $conn)
 {
     //remove nasty info about worker's bootstrap fail
     $conn->removeAllListeners('close');
     if ($this->output->isVeryVerbose()) {
         $conn->on('close', function () {
             $this->output->writeln('Status command requested');
         });
     }
     $conn->end(json_encode(['slaveCount' => $this->slaveCount, 'handledRequests' => $this->handledRequests]));
 }
コード例 #11
0
ファイル: ProcessManager.php プロジェクト: php-pm/php-pm
 /**
  * Handles incoming connections from $this->port. Basically redirects to a slave.
  *
  * @param Connection $incoming incoming connection from react
  */
 public function onWeb(Connection $incoming)
 {
     //preload sent data from $incoming to $buffer, otherwise it would be lost,
     //since getNextSlave is async.
     $redirectionActive = false;
     $connectionOpen = true;
     $incomingBuffer = '';
     $incoming->on('data', function ($data) use(&$redirectionActive, &$incomingBuffer) {
         if (!$redirectionActive) {
             $incomingBuffer .= $data;
         }
     });
     $redirectionTries = 0;
     $incoming->on('close', function () use(&$redirectionActive, &$redirectionTries, &$connectionOpen) {
         $connectionOpen = false;
     });
     $start = microtime(true);
     $redirectionTries++;
     $redirectRequest = function ($id) use(&$redirectRequest, &$incoming, &$incomingBuffer, &$redirectionActive, $start, &$redirectionTries, &$connectionOpen) {
         if (!$connectionOpen) {
             //since the initial connection of a client and getting a free worker the client meanwhile closed the connection,
             //so stop anything here.
             return;
         }
         if (!is_resource($incoming->stream)) {
             //Firefox closes somehow a connection directly after opening, at this state we need to check
             //whether the connection is still alive, to keep going. This check prevents the server from crashing
             return;
         }
         $took = microtime(true) - $start;
         if ($this->output->isVeryVerbose() && $took > 1) {
             $this->output->writeln(sprintf('<info>took abnormal %f seconds for choosing next free worker</info>', $took));
         }
         $slave =& $this->slaves[$id];
         $slave['busy'] = true;
         $slave['connections']++;
         $start = microtime(true);
         $stream = stream_socket_client($slave['host'], $errno, $errstr, $this->timeout);
         if (!$stream || !is_resource($stream)) {
             //we failed to connect to the worker. Maybe because of timeouts or it is in a crashed state
             //and is currently dieing.
             //since we don't know whether the worker is only very busy or dieing we just
             //set it back to available worker list. If it is really dying it will be
             //removed from the available worker list by itself during connection:close event.
             $slave['busy'] = false;
             $slave['connections']--;
             if ($this->output->isVeryVerbose()) {
                 $this->output->writeln(sprintf('<error>Connection to worker %d failed. Try #%d, took %fs. ' . 'Try increasing your timeout of %d. Error message: [%d] %s</error>', $id, $redirectionTries, microtime(true) - $start, $this->timeout, $errno, $errstr));
             }
             //Try next free client. It's important to do this here due to $incomingBuffer.
             $redirectionTries++;
             $this->getNextSlave($redirectRequest);
             return;
         }
         $connection = new \React\Socket\Connection($stream, $this->loop);
         $took = microtime(true) - $start;
         if ($this->output->isVeryVerbose() && $took > 1) {
             $this->output->writeln(sprintf('<info>took abnormal %f seconds for connecting to :%d</info>', $took, $slave['port']));
         }
         $start = microtime(true);
         $headersToReplace = ['X-PHP-PM-Remote-IP' => $incoming->getRemoteAddress()];
         $headerRedirected = false;
         if ($this->isHeaderEnd($incomingBuffer)) {
             $incomingBuffer = $this->replaceHeader($incomingBuffer, $headersToReplace);
             $headerRedirected = true;
             $connection->write($incomingBuffer);
         }
         $redirectionActive = true;
         $connection->on('close', function () use($incoming, &$slave, $start) {
             $took = microtime(true) - $start;
             if ($this->output->isVeryVerbose() && $took > 1) {
                 $this->output->writeln(sprintf('<info>took abnormal %f seconds for handling a connection</info>', $took));
             }
             $slave['busy'] = false;
             $slave['connections']--;
             $slave['requests']++;
             $incoming->end();
             /** @var Connection $connection */
             $connection = $slave['connection'];
             if ($slave['requests'] >= $this->maxRequests) {
                 $slave['ready'] = false;
                 $this->output->writeln(sprintf('Restart worker #%d because it reached maxRequests of %d', $slave['port'], $this->maxRequests));
                 $connection->close();
             } else {
                 if ($slave['closeWhenFree']) {
                     $connection->close();
                 }
             }
         });
         $connection->on('data', function ($buffer) use($incoming) {
             $incoming->write($buffer);
         });
         $incoming->on('data', function ($buffer) use($connection, &$incomingBuffer, $headersToReplace, &$headerRedirected) {
             if (!$headerRedirected) {
                 $incomingBuffer .= $buffer;
                 if ($this->isHeaderEnd($incomingBuffer)) {
                     $incomingBuffer = $this->replaceHeader($incomingBuffer, $headersToReplace);
                     $headerRedirected = true;
                     $connection->write($incomingBuffer);
                 } else {
                     //head has not completely received yet, wait
                 }
             } else {
                 //incomingBuffer has already been redirected, so redirect now buffer per buffer
                 $connection->write($buffer);
             }
         });
         $incoming->on('close', function () use($connection) {
             $connection->close();
         });
     };
     $this->getNextSlave($redirectRequest);
 }
コード例 #12
0
 protected function onConnect(SocketConnection $conn)
 {
     $conn->on('data', function ($data) use($conn) {
         $this->onData($conn, $data);
     });
 }
コード例 #13
0
ファイル: ttt_server.php プロジェクト: phpCedu/ReactExamples
 public function __construct(Connection $connection)
 {
     $this->connection = $connection;
     $this->connection->on('data', [$this, 'onData']);
     $this->connection->write('Welcome to Tic tac Toe, the game will start when two players are connected!' . PHP_EOL);
 }