/** * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $host = $input->getOption('listen-host'); $port = $input->getOption('listen-port'); $pathPrefix = $input->getOption('path-prefix'); $workingDir = $this->getWorkingDir($input); $output->writeln('<info>Client started:</info>'); $output->writeln(' <comment>listen:' . '</comment> ' . $host . ':' . $port); $output->writeln(' <comment>working-dir:' . '</comment> ' . $workingDir); $client = new ModuleClient($workingDir); $loop = EventLoopFactory::create(); $socket = new SocketServer($loop); $http = new HttpServer($socket); $http->on('request', function (HttpRequest $request, HttpResponse $response) use($input, $client, $workingDir, $pathPrefix) { $path = $request->getPath(); if ($pathPrefix) { $path = str_replace($pathPrefix, '', $path); } if (in_array($path, array('/call', '/status', '/update-status'))) { $response->writeHead(200, array('Content-Type' => 'application/json')); $params = $request->getQuery(); try { switch ($path) { case '/call': $headers = $request->getHeaders(); $url = 'http://' . $headers['Host'] . ':' . $input->getOption('listen-port'); $resp = $client->callMethod($params, $url . '/update-status'); break; case '/status': $resp = $client->getStatus($params); break; case '/update-status': $resp = $client->updateStatus($params); break; } } catch (\Exception $e) { $resp = array('success' => false, 'msg' => $e->getMessage()); } $resp = json_encode($resp); if (isset($params['callback'])) { $resp = $params['callback'] . '(' . $resp . ')'; } $response->end($resp); } else { if ($input->getOption('ui')) { if ('/api' == $path) { $response->writeHead(200, array('Content-Type' => 'application/json')); $params = $request->getQuery(); try { $resp = $client->apiMethod($params); } catch (\Exception $e) { $resp = array('success' => false, 'msg' => $e->getMessage()); } $response->end(json_encode($resp)); } else { $response->writeHead(200, array('Content-Type' => 'text/html')); try { $resp = $this->getTwigEnv()->render('index.html.twig', array('pathPrefix' => $pathPrefix ?: '')); } catch (\Exception $e) { $resp = $e->getMessage(); } $response->end($resp); } } else { $response->writeHead(200, array('Content-Type' => 'text/html')); $response->end('Client started'); } } }); $socket->listen($port, $host); $loop->run(); }