private function setupSocketListeners()
 {
     $connectionListeners = array();
     foreach ($this->socketListeners as $listener) {
         /** @var SocketListenerInterface $service */
         $service = $this->getContainer()->get($listener);
         if (!$service instanceof SocketListenerInterface) {
             throw new \Exception("Socket Listener Services must implement JDare/ClankBundle/Server/SocketListenerInterface");
         }
         foreach ((array) $service->getListeners() as $event => $callback) {
             if ($event == 'connection') {
                 $this->socket->on('connection', $callback);
             } elseif ($event == 'error') {
                 $this->socket->on('error', $callback);
             } else {
                 if (!isset($connectionListeners[$event])) {
                     $connectionListeners[$event] = array();
                 }
                 $connectionListeners[$event][] = $callback;
             }
         }
     }
     if (!empty($connectionListeners)) {
         $this->socket->on('connection', function (ConnectionInterface $conn) use(&$connectionListeners) {
             $conn->on('data', function ($data) use($conn, &$connectionListeners) {
                 if (isset($connectionListeners[$data])) {
                     foreach ($connectionListeners[$data] as $callback) {
                         $callback($conn);
                     }
                 }
             });
         });
     }
 }
 /**
  * @param int $port
  * @param string $host
  */
 public function __construct($port, $host = '127.0.0.1')
 {
     $this->host = $host;
     $this->port = $port;
     $this->loop = LoopFactory::create();
     $this->socket = new SocketServer($this->loop);
     $this->socket->on('connection', array($this, 'onConnection'));
 }
 public function start()
 {
     $loop = React\EventLoop\Factory::create();
     $socket = new React\Socket\Server($loop);
     $server = $this;
     $socket->on(self::CONNECTION, function (React\Socket\Connection $connection) use(&$server) {
         $server->connectionEvent($connection);
         $connection->on(SyncDaemonServer::DATA, function ($data) use(&$connection, &$server) {
             list($command, $name) = explode(' ', $data);
             if ($command == SyncDaemonServer::ACQUIRE) {
                 $server->acquireCommand($connection, $name);
             }
             if ($command == SyncDaemonServer::RELEASE) {
                 $server->releaseCommand($connection, $name);
             }
         });
         $connection->on(SyncDaemonServer::CLOSE, function () use(&$connection, &$server) {
             $server->closeEvent($connection);
         });
         $connection->write(SyncDaemonServer::ACCEPT);
     });
     //debug
     //$loop->addPeriodicTimer(1, function () use (&$server) {
     //    var_dump(count($server->connections) . '-' . count($server->locks));
     //});
     $socket->listen($this->port, $this->host);
     $loop->run();
 }
Exemple #4
0
 public function __construct(QueueContextInterface $queueContext, LoopInterface $eventLoop, $port)
 {
     $this->queueContext = $queueContext;
     $server = new Server($eventLoop);
     $server->on('connection', [$this, 'onConnection']);
     $server->listen($port);
 }
Exemple #5
0
 /**
  * Starts the main loop. Blocks.
  */
 public function run()
 {
     Debug::enable();
     //make whatever is necessary to disable all stuff that could buffer output
     ini_set('zlib.output_compression', 0);
     ini_set('output_buffering', 0);
     ini_set('implicit_flush', 1);
     ob_implicit_flush(1);
     $this->loop = \React\EventLoop\Factory::create();
     $this->controller = new React\Server($this->loop);
     $this->controller->on('connection', array($this, 'onSlaveConnection'));
     $this->controllerHost = $this->getNewControllerHost();
     $this->controller->listen(5500, $this->controllerHost);
     $this->web = new \React\Socket\Server($this->loop);
     $this->web->on('connection', array($this, 'onWeb'));
     $this->web->listen($this->port, $this->host);
     $this->tcpConnector = new \React\SocketClient\TcpConnector($this->loop);
     $pcntl = new \MKraemer\ReactPCNTL\PCNTL($this->loop);
     $pcntl->on(SIGTERM, [$this, 'shutdown']);
     $pcntl->on(SIGINT, [$this, 'shutdown']);
     $pcntl->on(SIGCHLD, [$this, 'handleSigchld']);
     $pcntl->on(SIGUSR1, [$this, 'restartWorker']);
     if ($this->isDebug()) {
         $this->loop->addPeriodicTimer(0.5, function () {
             $this->checkChangedFiles();
         });
     }
     $this->isRunning = true;
     $loopClass = (new \ReflectionClass($this->loop))->getShortName();
     $this->output->writeln("<info>Starting PHP-PM with {$this->slaveCount} workers, using {$loopClass} ...</info>");
     for ($i = 0; $i < $this->slaveCount; $i++) {
         $this->newInstance(5501 + $i);
     }
     $this->loop->run();
 }
 public function addListener($host = '127.0.0.1', $port = 8080, $use_ssl = false, $cert = null)
 {
     $proxy = new Server($this->loop);
     $proxy->on('connection', new ConnectionHandler($this));
     $context = !$use_ssl ? [] : ['ssl' => ['local_cert' => $cert === null ? __DIR__ . '/../certificate.pem' : $cert, 'allow_self_signed' => true, 'verify_peer' => false]];
     $proxy->listen($port, $host, $context);
 }
Exemple #7
0
 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();
 }
Exemple #8
0
 /**
  * Starts the main loop. Blocks.
  */
 public function run()
 {
     Debug::enable();
     gc_disable();
     //necessary, since connections will be dropped without reasons after several hundred connections.
     $this->loop = \React\EventLoop\Factory::create();
     $this->controller = new \React\Socket\Server($this->loop);
     $this->controller->on('connection', array($this, 'onSlaveConnection'));
     $this->controller->listen(5500);
     $this->web = new \React\Socket\Server($this->loop);
     $this->web->on('connection', array($this, 'onWeb'));
     $this->web->listen($this->port, $this->host);
     $this->tcpConnector = new \React\SocketClient\TcpConnector($this->loop);
     $pcntl = new \MKraemer\ReactPCNTL\PCNTL($this->loop);
     $pcntl->on(SIGTERM, [$this, 'shutdown']);
     $pcntl->on(SIGINT, [$this, 'shutdown']);
     if ($this->isDebug()) {
         $this->loop->addPeriodicTimer(0.5, function () {
             $this->checkChangedFiles();
         });
     }
     $this->isRunning = true;
     $loopClass = (new \ReflectionClass($this->loop))->getShortName();
     $this->output->writeln("<info>Starting PHP-PM with {$this->slaveCount} workers, using {$loopClass} ...</info>");
     for ($i = 0; $i < $this->slaveCount; $i++) {
         $this->newInstance(5501 + $i);
     }
     $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);
 }
Exemple #10
0
 /**
  * @param NetworkAddressInterface $localAddr
  * @param MessageFactory $messageFactory
  * @param Server $server
  * @param LoopInterface $loop
  */
 public function __construct(NetworkAddressInterface $localAddr, MessageFactory $messageFactory, Server $server, LoopInterface $loop)
 {
     $this->local = $localAddr;
     $this->messageFactory = $messageFactory;
     $this->server = $server;
     $this->loop = $loop;
     $server->on('connection', [$this, 'handleIncomingPeer']);
 }
Exemple #11
0
 /**
  * Listener constructor.
  * @param ConnectionParams $params
  * @param MessageFactory $messageFactory
  * @param Server $server
  * @param LoopInterface $loop
  */
 public function __construct(ConnectionParams $params, MessageFactory $messageFactory, Server $server, LoopInterface $loop)
 {
     $this->params = $params;
     $this->messageFactory = $messageFactory;
     $this->server = $server;
     $this->loop = $loop;
     $server->on('connection', [$this, 'handleIncomingPeer']);
 }
 public function handleRouterStart(RouterStartEvent $event)
 {
     $socket = new Server($this->loop);
     $socket->on('connection', [$this, "handleConnection"]);
     Logger::info($this, "Raw socket listening on " . $this->address . ":" . $this->port);
     $socket->listen($this->port, $this->address);
     $this->server = $socket;
 }
 /**
  * Start transport provider
  *
  * @param \Thruway\Peer\AbstractPeer $peer
  * @param \React\EventLoop\LoopInterface $loop
  */
 public function startTransportProvider(AbstractPeer $peer, LoopInterface $loop)
 {
     $this->peer = $peer;
     $this->loop = $loop;
     $socket = new Server($loop);
     $socket->on('connection', [$this, "handleConnection"]);
     $socket->listen($this->port, $this->address);
 }
Exemple #14
0
 public function listen($port)
 {
     $server = new SocketServer($this->loop);
     $server->on('connection', function (SocketConnection $connection) {
         try {
             $this->connectionManager->accept($connection);
         } catch (\Exception $e) {
             $this->logger->error('Connection failed', ['error' => $e->getMessage()]);
         }
     });
     $server->listen($port, '0.0.0.0');
     $this->logger->info('Started socket server', ['port' => $port]);
 }
Exemple #15
0
 public function run()
 {
     $this->loop = \React\EventLoop\Factory::create();
     $this->controller = new \React\Socket\Server($this->loop);
     $this->controller->on('connection', array($this, 'onSlaveConnection'));
     $this->controller->listen(5500);
     $this->web = new \React\Socket\Server($this->loop);
     $this->web->on('connection', array($this, 'onWeb'));
     $this->web->listen($this->port, $this->host);
     for ($i = 0; $i < $this->slaveCount; $i++) {
         $this->newInstance();
     }
     $this->run = true;
     $this->loop();
 }
Exemple #16
0
 /**
  * @param $port
  * @param string $binding
  * @return $this
  * @throws \React\Socket\ConnectionException
  */
 public function listen($port, $binding = "0.0.0.0")
 {
     if (!empty($this->routes)) {
         $this->dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector &$router) {
             foreach ($this->routes as $route) {
                 call_user_func_array([$router, 'addRoute'], $route);
             }
         });
     }
     $this->io->on('connection', function (ConnectionInterface $conn) {
         $this->onConnection($conn);
     });
     $this->io->listen($port, $binding);
     return $this;
 }
Exemple #17
0
 public function run()
 {
     $this->loop = \React\EventLoop\Factory::create();
     $this->controller = new \React\Socket\Server($this->loop);
     $this->controller->on('connection', array($this, 'onSlaveConnection'));
     $this->controller->listen($this->masterPort);
     echo sprintf('Master process running on %d', $this->masterPort) . PHP_EOL;
     $this->web = new \React\Socket\Server($this->loop);
     $this->web->on('connection', array($this, 'onWeb'));
     $this->web->listen($this->port, $this->host);
     echo sprintf('LB running on %d', $this->port) . PHP_EOL;
     for ($i = 0; $i < $this->slaveCount; $i++) {
         $this->newInstance();
     }
     $this->run = true;
     $this->loop();
 }
Exemple #18
0
 public function listen()
 {
     $params = $this->protocol->parseArgs(func_get_args());
     if (!isset($params['host'])) {
         $params['host'] = '127.0.0.1';
     }
     if (!isset($params['port'])) {
         throw new \Exception("For now we only support TCP connections to a defined port");
     }
     $that = $this;
     $server = new Server($this->loop);
     $server->on('connection', function ($conn) use($that, $params) {
         $that->handleConnection($conn, $params);
     });
     $server->listen($params['port'], $params['host']);
     return $server;
 }
Exemple #19
0
 public function testConnect()
 {
     $loop = new StreamSelectLoop();
     $deferred = new Deferred();
     $deferred->promise()->then(function ($value) use($loop) {
         $this->assertEquals(1, $value);
         $loop->stop();
     }, function () {
         $this->fail('Promise was rejected');
     });
     $server = new Server($loop);
     $server->listen(54321, '0.0.0.0');
     $server->on('connection', function (Stream $stream) use($deferred, $server) {
         $deferred->resolve(1);
         $server->shutdown();
     });
     $request = new RequestFactory();
     $connector = new TcpConnector($loop);
     $client = new Client($connector, $request);
     $client->connect('127.0.0.1', 54321);
     $loop->run();
 }
Exemple #20
0
 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();
 }
Exemple #21
0
 /**
  * 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();
 }
Exemple #22
0
    {
        $ui = Ui::printStatus($this->game);
        $this->connection->write($ui);
        echo $ui;
    }
}
$loop = Factory::create();
$socket = new Server($loop);
$players = [];
$socket->on('connection', function (Connection $conn) use(&$players, $socket) {
    if (count($players) < 2) {
        $players[] = new PlayerConnection($conn);
    }
    if (count($players) == 2) {
        $deferred = new Deferred();
        $deferred->promise()->then(function ($results) use(&$players, $socket) {
            foreach ($results as $result) {
                foreach ($players as $player) {
                    if ($player === $result[0]) {
                        $player->getConnection()->end('You ' . $result[1] . PHP_EOL);
                    }
                }
            }
            $socket->shutdown();
        });
        $game = new Game($players[0], $players[1]);
        $game->start($deferred);
    }
});
$socket->listen(1337, '0.0.0.0');
$loop->run();
Exemple #23
0
 /**
  * Start & init the API
  */
 public function listen()
 {
     // Init API
     $this->apiManager->init();
     if (!$this->apiManager->connect()) {
         throw new \RuntimeException('There is no ready client, aborted');
     }
     // Init server
     $loop = $this->apiManager->getLoop();
     $socket = new SocketServer($loop);
     $socket->on('connection', function ($conn) {
         /** @var Connection $conn */
         $this->logger->debug(sprintf('Client [%s] is connected to server', $conn->getRemoteAddress()));
         // On receive data
         $conn->on('data', function ($rawData) use($conn) {
             $this->logger->debug(sprintf('Client sent: %s', $rawData));
             $data = json_decode($rawData, true);
             $format = null;
             if (isset($data['format'])) {
                 $format = $data['format'];
             }
             try {
                 if (!$this->isValidInput($data)) {
                     throw new MalformedClientInputException('The input sent to the server is maformed');
                 }
                 $conn->on('api-response', function ($response) use($conn, $format) {
                     $conn->end($this->format($response, $format));
                 });
                 $conn->on('api-error', function (ServerException $e) use($conn, $format) {
                     $conn->end($this->format($e->toArray(), $format));
                     if ($e instanceof RequestTimeoutException) {
                         $e->getClient()->reconnect();
                         // Force doing heartbeats to check if another client is timed out
                         $this->apiManager->doHeartbeats();
                     }
                 });
                 $this->apiManager->getRouter()->process($this->apiManager, $conn, $data);
             } catch (ServerException $e) {
                 $this->logger->error('Client [' . $conn->getRemoteAddress() . ']: ' . $e->getMessage());
                 $conn->end($this->format($e->toArray(), $format));
             }
         });
     });
     $port = ConfigurationLoader::get('server.port');
     $bind = ConfigurationLoader::get('server.bind');
     $this->logger->info(sprintf('Listening on %s:%d', $bind == '0.0.0.0' ? '*' : $bind, $port));
     $socket->listen($port, $bind);
     $loop->run();
 }
 /**
  * Start server
  *
  * @throws RuntimeException
  */
 public function run()
 {
     try {
         $this->loop->addPeriodicTimer($this->timePeriod, $this->getPeriodicTimerCallback());
         //listening of the ports
         foreach ($this->listen as $port) {
             $socket = new Server($this->loop);
             //initialize socket
             $socket->on('connection', function (Connection $conn) {
                 $this->conns->attach($conn);
                 $conn->on('data', function ($data, $conn) {
                     //$request insteadof React\Http\Request
                     list($request, $body) = (new RequestHeaderParser())->parseRequest($data);
                     $this->conns->attach($conn, new LongPooling\ConnectionInfo($request, $body));
                 });
                 $conn->on('end', function ($conn) {
                     $this->conns->detach($conn);
                 });
             });
             $socket->listen($port);
         }
         $this->loop->run();
     } catch (Exception $e) {
         throw new RuntimeException("Server Run Exception", 301, $e);
     }
 }
Exemple #25
0
 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();
 }
Exemple #26
0
// sent for each connection and will print the average throughput once the
// connection closes.
//
// $ php examples/03-benchmark.php 8000
// $ telnet localhost 8000
// $ echo hello world | nc -v localhost 8000
// $ dd if=/dev/zero bs=1M count=1000 | nc -v localhost 8000
use React\EventLoop\Factory;
use React\Socket\Server;
use React\Socket\ConnectionInterface;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
$server = new Server($loop);
$server->listen(isset($argv[1]) ? $argv[1] : 0);
$server->on('connection', function (ConnectionInterface $conn) use($loop) {
    echo '[connected]' . PHP_EOL;
    // count the number of bytes received from this connection
    $bytes = 0;
    $conn->on('data', function ($chunk) use(&$bytes) {
        $bytes += strlen($chunk);
    });
    // report average throughput once client disconnects
    $t = microtime(true);
    $conn->on('close', function () use($conn, $t, &$bytes) {
        $t = microtime(true) - $t;
        echo '[disconnected after receiving ' . $bytes . ' bytes in ' . round($t, 3) . 's => ' . round($bytes / $t / 1024 / 1024, 1) . ' MiB/s]' . PHP_EOL;
    });
});
$server->on('error', 'printf');
echo 'bound to ' . $server->getPort() . PHP_EOL;
$loop->run();
Exemple #27
0
use React\EventLoop\Factory;
use React\Socket\Server;
use React\Socket\ConnectionInterface;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
$server = new Server($loop);
$server->listen(isset($argv[1]) ? $argv[1] : 0, '0.0.0.0');
$clients = array();
$server->on('connection', function (ConnectionInterface $client) use(&$clients) {
    // keep a list of all connected clients
    $clients[] = $client;
    $client->on('close', function () use($client, &$clients) {
        unset($clients[array_search($client, $clients)]);
    });
    // whenever a new message comes in
    $client->on('data', function ($data) use($client, &$clients) {
        // remove any non-word characters (just for the demo)
        $data = trim(preg_replace('/[^\\w\\d \\.\\,\\-\\!\\?]/u', '', $data));
        // ignore empty messages
        if ($data === '') {
            return;
        }
        // prefix with client IP and broadcast to all connected clients
        $data = $client->getRemoteAddress() . ': ' . $data . PHP_EOL;
        foreach ($clients as $client) {
            $client->write($data);
        }
    });
});
echo 'Listening on ' . $server->getPort() . PHP_EOL;
$loop->run();
 protected function initEvent(SocketServer $socket)
 {
     $socket->on('connection', function (SocketConnection $conn) {
         $this->onConnect($conn);
     });
 }
Exemple #29
0
 public function masterServer($bindMasterTo)
 {
     cli_set_process_title("mpcmf/console server:run/master -b {$bindMasterTo['host']} -p {$bindMasterTo['port']}");
     $output = $this->output;
     //MPCMF_DEBUG && $output->writeln('<error>[MASTER]</error> Preparing server');
     $loop = Factory::create();
     $dnsResolverFactory = new reactResolver();
     $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);
     $connector = new Connector($loop, $dns);
     $output->writeln('<error>[MASTER]</error> Binding callables and building socketServer');
     $socketServer = new reactSocketServer($loop);
     $clientId = null;
     $socketServer->on('connection', function (Connection $clientConnection) use($connector, $output, $clientId, $loop) {
         $clientConnection->pause();
         MPCMF_DEBUG && ($clientId = spl_object_hash($clientConnection));
         do {
             $threadKey = array_rand($this->threads);
             if ($this->threads[$threadKey]->isAlive()) {
                 break;
             }
             $loop->tick();
         } while (true);
         $childPort = json_decode($threadKey, true)['port'];
         //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Client connected, using port {$childPort}");
         $clientConnection->on('end', function () use($clientConnection, $clientId, $output) {
             //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Client connection ending");
         });
         $clientConnection->on('close', function () use($clientConnection, $clientId, $output) {
             //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Client connection closed");
         });
         /** @var \React\Promise\FulfilledPromise|\React\Promise\Promise|\React\Promise\RejectedPromise $childConnection */
         $childConnection = $connector->create($this->childHost, $childPort);
         $childConnection->then(function (reactStream $childStream) use($clientConnection, $childConnection, $output, $clientId) {
             $childStream->pause();
             //MPCMF_DEBUG && $output->writeln('<error>=================== ' . spl_object_hash($childStream) . ' CHILD STREAM OPEN </error>');
             $childStream->on('end', function () use($clientConnection, $childConnection, $childStream, $output, $clientId) {
                 //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Child closed connection");
                 //MPCMF_DEBUG && $output->writeln('<error>=================== ' . spl_object_hash($childStream) . ' CHILD STREAM CLOSE</error>');
                 $childStream->close();
                 $clientConnection->getBuffer()->on('full-drain', function () use($clientConnection, $output, $clientId) {
                     //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Buffer is empty, closing client connection");
                     $clientConnection->close();
                 });
             });
             $childStream->on('data', function ($data) use($clientConnection, $childConnection, $childStream, $output, $clientId) {
                 //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Response from child received");
                 //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Sending response to client");
                 $clientConnection->write($data);
             });
             $childStream->resume();
             $clientConnection->on('data', function ($data) use($clientConnection, $childConnection, $output, $clientId, $childStream) {
                 //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Client data received");
                 //MPCMF_DEBUG && $output->writeln("<error>[MASTER:{$clientId}]</error> Sending request to child");
                 $childStream->write($data);
             });
             $clientConnection->resume();
         });
     });
     $output->writeln("<error>[MASTER]</error> Starting server on {$bindMasterTo['host']}:{$bindMasterTo['port']}");
     $socketServer->listen($bindMasterTo['port'], $bindMasterTo['host']);
     $loop->addPeriodicTimer(1.0, [$this, 'checkThreads']);
     $loop->run();
 }
Exemple #30
0
<?php

// Just start this server and connect to it. Everything you send to it will be
// sent back to you.
//
// $ php examples/01-echo.php 8000
// $ telnet localhost 8000
use React\EventLoop\Factory;
use React\Socket\Server;
use React\Socket\ConnectionInterface;
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
$server = new Server($loop);
$server->listen(isset($argv[1]) ? $argv[1] : 0);
$server->on('connection', function (ConnectionInterface $conn) use($loop) {
    echo '[connected]' . PHP_EOL;
    $conn->pipe($conn);
});
echo 'Listening on ' . $server->getPort() . PHP_EOL;
$loop->run();