Example #1
0
 /**
  * Constructor
  *
  * @param OutputInterface $output  Output
  * @param string          $docroot Docroot
  * @param string          $env     Environment
  * @param bool            $debug   Debug
  * @param int             $port    Port
  */
 public function __construct(OutputInterface $output, $docroot, $env, $debug, $port = null)
 {
     $repository = new PhpRepository();
     if (!$port) {
         $port = 8000;
     }
     $this->output = $output;
     $this->env = $env;
     $this->debug = $debug;
     $this->port = $port;
     $this->loop = new StreamSelectLoop();
     $socketServer = new ReactSocketServer($this->loop);
     $httpServer = new ReactHttpServer($socketServer);
     $httpServer->on("request", function ($request, $response) use($repository, $docroot, $output) {
         $path = $docroot . '/' . ltrim(rawurldecode($request->getPath()), '/');
         if (is_dir($path)) {
             $path .= '/index.html';
         }
         if (!file_exists($path)) {
             HttpServer::logRequest($output, 404, $request);
             $response->writeHead(404, ['Content-Type' => 'text/html']);
             return $response->end(implode('', ['<h1>404</h1>', '<h2>Not Found</h2>', '<p>', 'The embedded <a href="https://sculpin.io">Sculpin</a> web server could not find the requested resource.', '</p>']));
         }
         $type = 'application/octet-stream';
         if ('' !== ($extension = pathinfo($path, PATHINFO_EXTENSION))) {
             if ($guessedType = $repository->findType($extension)) {
                 $type = $guessedType;
             }
         }
         HttpServer::logRequest($output, 200, $request);
         $response->writeHead(200, array("Content-Type" => $type));
         $response->end(file_get_contents($path));
     });
     $socketServer->listen($port, '0.0.0.0');
 }
Example #2
0
 public function listen($port, $host = '0.0.0.0')
 {
     $http = new React\Http\Server($this->socket, $this->loop);
     $http->on('request', $this->requestHandler);
     $this->socket->listen($port, $host);
     $this->loop->run();
 }
Example #3
0
 /**
  * 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;
 }
Example #4
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();
 }
 /**
  * Creates a new \React\Http\Server and runs it
  *
  * @param int $port
  */
 public function listen($port)
 {
     $socket = new SocketServer($this->loop);
     $server = new HttpServer($socket);
     $server->on('request', $this->requestHandler);
     $socket->listen($port);
 }
Example #6
0
 private function initHttpServer()
 {
     $socket = new ServerSocket($this->getLoop());
     $socket->listen($this->config->getPort(), $this->config->getHost());
     $http = new HttpServer($socket, $this->getLoop());
     $http->on('request', [$this, 'handleRequest']);
 }
Example #7
0
 public function __construct(LoopInterface $loop, ProxyWebSocketController $controller, $clientId)
 {
     $this->clientId = $clientId;
     $this->controller = $controller;
     $this->socket = $this->createSocket($loop);
     $this->http = $this->createHttpServer($this->socket);
     $this->http->on('request', [$this, 'handleHttpRequest']);
 }
 /**
  * Constructor
  * 
  * @param array $authRealms
  * @param \React\Http\Server $http
  * @param string $clientId
  * @param string $clientSecret
  */
 public function __construct($authRealms, $http, $clientId, $clientSecret)
 {
     $this->clientId = $clientId;
     $this->clientSecret = $clientSecret;
     parent::__construct($authRealms);
     //Register Http request event
     $http->on('request', [$this, "onHttpRequest"]);
 }
Example #9
0
 /**
  * start the loop
  */
 public function start()
 {
     $this->loop = React\EventLoop\Factory::create();
     $socket = new React\Socket\Server($this->loop);
     $http = new React\Http\Server($socket);
     $http->on('request', $function = $this->requestHandler->getHandlerFunction());
     $socket->listen($this->requestHandler->getPort(), $this->requestHandler->getHost());
     $this->loop->run();
 }
Example #10
0
 /**
  * Starts the server
  */
 public function start()
 {
     $loop = Factory::create();
     $socketServer = new SocketServer($loop);
     $httpServer = new HttpServer($socketServer);
     $httpServer->on('request', array($this, 'serverCallback'));
     $socketServer->listen($this->port, $this->host);
     fwrite(STDOUT, 'Starting server at ' . $this->host . ':' . $this->port);
     $loop->run();
 }
Example #11
0
 /**
  * @return void
  */
 public function loop()
 {
     $loop = Factory::create();
     $socket = new SocketServer($loop);
     $http = new HttpServer($socket);
     $this->getEventManager()->attach(MvcEvent::EVENT_FINISH, [$this, 'renderRequest'], -1000);
     $http->on('request', [$this, 'processRequest']);
     $socket->listen($this->serverOptions->getPort(), $this->serverOptions->getHost());
     $loop->run();
 }
Example #12
0
 public function listen($port, $host = '127.0.0.1')
 {
     $loop = Factory::create();
     $socket = new SocketServer($loop);
     $http = new HttpServer($socket);
     $http->on('request', $this->app);
     echo "Server running on {$host}:{$port}\n";
     $socket->listen($port, $host);
     $loop->run();
 }
Example #13
0
 public function run($port)
 {
     self::$port = $port;
     $loop = new StreamSelectLoop();
     $socket = new SocketServer($loop);
     $http = new HttpServer($socket, $loop);
     $http->on('request', [$this, 'serve']);
     $socket->listen($port);
     echo "Reactavel server started on localhost:{$port}\n";
     $loop->run();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->input = $input;
     $this->output = $output;
     $loop = React\EventLoop\Factory::create();
     $socket = new React\Socket\Server($loop);
     $http = new React\Http\Server($socket);
     $http->on('request', function (React\Http\Request $request, React\Http\Response $response) {
         $this->handleRequest($request, $response);
     });
     $socket->listen(8000);
     $loop->run();
 }
 /**
  * StaticWebServer constructor.
  *
  * @param Server               $httpServer
  * @param string               $webroot
  * @param LoggerInterface|null $logger
  */
 public function __construct(Server $httpServer, $webroot, LoggerInterface $logger = null)
 {
     if (!file_exists($webroot)) {
         throw new \InvalidArgumentException('The specified webroot path does not exist');
     }
     $this->httpServer = $httpServer;
     $this->webroot = $webroot;
     $this->logger = $logger;
     // Attach the request handler
     $this->httpServer->on('request', [$this, 'handleRequest']);
     // Configure the content type parser
     $this->contentTypeParser = new ContentTypeParser();
 }
Example #16
0
 public function testResponseContainsPoweredByHeader()
 {
     $io = new ServerStub();
     $server = new Server($io);
     $server->on('request', function ($request, $response) {
         $response->writeHead();
         $response->end();
     });
     $conn = new ConnectionStub();
     $io->emit('connection', array($conn));
     $data = $this->createGetRequest();
     $conn->emit('data', array($data));
     $this->assertContains("\r\nX-Powered-By: React/alpha\r\n", $conn->getData());
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $kernel = new AppKernel($environment = $input->getOption("environment"), $environment !== "prod");
     $kernel->boot();
     $loop = Factory::create();
     /** @var Container $container */
     $container = $kernel->getContainer();
     $container->set("react.loop", $loop);
     $socket = new Socket($loop);
     $http = new Server($socket);
     $http->on("request", function (Request $request, Response $response) use($kernel, $loop) {
         $headers = $request->getHeaders();
         $cookies = [];
         if (isset($headers["Cookie"])) {
             foreach ((array) $headers["Cookie"] as $cookieHeader) {
                 foreach (explode(";", $cookieHeader) as $cookie) {
                     list($name, $value) = explode("=", trim($cookie), 2);
                     $cookies[$name] = urldecode($value);
                 }
             }
         }
         $symfonyRequest = new SymfonyRequest($request->getQuery(), [], [], $cookies, [], ["REQUEST_URI" => $request->getPath(), "SERVER_NAME" => explode(":", $headers["Host"])[0], "REMOTE_ADDR" => $request->remoteAddress, "QUERY_STRING" => http_build_query($request->getQuery())], null);
         $symfonyRequest->headers->replace($headers);
         $symfonyResponse = $kernel->handle($symfonyRequest);
         if ($kernel instanceof TerminableInterface) {
             $kernel->terminate($symfonyRequest, $symfonyResponse);
         }
         if ($symfonyResponse instanceof PromiseInterface) {
             $symfonyResponse->then(function (SymfonyResponse $symfonyResponse) use($response) {
                 $this->send($response, $symfonyResponse);
             }, function ($error) use($loop, $response) {
                 echo "Exception: ", (string) $error, "\n";
                 $response->writeHead(500, ["Content-Type" => "text/plain"]);
                 $response->end("500 Internal Server Error");
                 $loop->stop();
             });
         } elseif ($symfonyResponse instanceof SymfonyResponse) {
             $this->send($response, $symfonyResponse);
         } else {
             echo "Unsupported response type: ", get_class($symfonyResponse), "\n";
             $response->writeHead(500, ["Content-Type" => "text/plain"]);
             $response->end("500 Internal Server Error");
             $loop->stop();
         }
     });
     $socket->listen($port = $input->getOption("port"), $host = $input->getOption("host"));
     echo "Listening to {$host}:{$port}\n";
     $loop->run();
 }
Example #18
0
 /**
  * @param int    $port
  * @param string $host
  */
 public function listen($port, $host)
 {
     $this->http->on('request', function (ReactRequest $request, ReactResponse $response) {
         return $this->onRequest($request, $response);
     });
     $this->logger->info("Phiremock http server listening on {$host}:{$port}");
     $this->socket->listen($port, $host);
     // Dispatch pending signals periodically
     if (function_exists('pcntl_signal_dispatch')) {
         $this->loop->addPeriodicTimer(0.5, function () {
             pcntl_signal_dispatch();
         });
     }
     $this->loop->run();
 }
Example #19
0
 public function createServer(HttpServerInterface $http = null)
 {
     if ($http === null) {
         $this->loop = $loop = LoopFactory::create();
         $this->socket = $socket = new SocketServer($loop);
         $this->http = $http = new Server($socket, $loop);
     }
     $http->on('request', function ($http_request, $http_response) {
         $app = $this;
         $request = new Request($http_request);
         $response = new Response($http_response, $request);
         $app($request, $response);
     });
     return $this;
 }
Example #20
0
 /**
  * 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();
     $this->socket = new SocketServer($this->loop);
     $http = new HttpServer($this->socket, $this->loop);
     $http->on('request', $this->handleRequest($kernel));
     return $this;
 }
Example #21
0
 public function testServerRespondsToExpectContinue()
 {
     $io = new ServerStub();
     $server = new Server($io);
     $conn = new ConnectionStub();
     $io->emit('connection', array($conn));
     $requestReceived = false;
     $postBody = '{"React":true}';
     $httpRequestText = $this->createPostRequestWithExpect($postBody);
     $conn->emit('data', array($httpRequestText));
     $server->on('request', function ($request, $_) use(&$requestReceived, $postBody) {
         $requestReceived = true;
         $this->assertEquals($postBody, $request->getBody());
     });
     // If server received Expect: 100-continue - the client won't send the body right away
     $this->assertEquals(false, $requestReceived);
     $this->assertEquals("HTTP/1.1 100 Continue\r\n\r\n", $conn->getData());
     $conn->emit('data', array($postBody));
     $this->assertEquals(true, $requestReceived);
 }
Example #22
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $port = $input->getOption('port');
     $configPath = $input->getOption('config');
     if (!$configPath) {
         if (!file_exists($configPath)) {
             throw new \Exception('Missing configuration file.');
         }
     }
     $config = new Config($configPath);
     $this->httpKernel = new HttpKernel($config);
     $loop = React\EventLoop\Factory::create();
     $socket = new React\Socket\Server($loop);
     $http = new React\Http\Server($socket);
     $http->on('request', array($this, 'handleRequest'));
     $socket->listen($port);
     $output->writeln('<info>Configuration file: ' . realpath($configPath) . '</info>');
     $output->writeln('<info>Server running on http://localhost:' . $port . '/</info>');
     $loop->run();
 }
Example #23
0
 public function listen($port, $host = '127.0.0.1')
 {
     self::$loop = Factory::create();
     $socket = new SocketServer(self::$loop);
     $http = new HttpServer($socket);
     $queue = \GuzzleHttp\Promise\queue();
     $queue->run();
     self::$loop->addPeriodicTimer(0, [$queue, 'run']);
     //Add Intervals
     $intervals = Interval::getIntervals();
     if ($intervals instanceof \ArrayIterator) {
         foreach ($intervals as $interval) {
             self::$loop->addPeriodicTimer($interval->getTime(), $interval->getCallback());
         }
     }
     $http->on('request', $this->app);
     echo "Server running on {$host}:{$port}\n";
     $socket->listen($port, $host);
     self::$loop->run();
 }
Example #24
0
 /**
  * Start the server.
  */
 public function run()
 {
     $this->logger->info("Starting server on {$this->host}:{$this->port}");
     $this->socket = new ServerSocket($this->loop);
     $this->http = new HttpServer($this->socket);
     $this->http->on('request', function (Request $request, Response $response) {
         $bodyParser = BodyParserFactory::create($request);
         $bodyParser->on('body', function ($body) use($request, $response) {
             $this->handle($request, $body, $response);
         });
     });
     $this->socket->listen($this->port, $this->host);
     $this->loop->run();
 }
Example #25
0
 public function boot()
 {
     if (!$this->port) {
         // The server doesn't run.
         return;
     }
     $this->socket = new ReactSocketServer($this->eventLoop);
     $http = new ReactHttpServer($this->socket);
     $this->socket->listen($this->port, $this->host);
     $routes = $this->router->getRoutes();
     $http->on('request', function ($request, $response) use($routes) {
         // check api key.
         if (count($this->apiKeys) > 0) {
             $query = $request->getQuery();
             if (!isset($query['apiKey']) || !isset($this->apiKeys[$query['apiKey']])) {
                 $response->writeHead(401, array('Content-Type' => 'text/plain'));
                 $response->end("Unauthorized\n");
                 $this->outputAccessLog($request, 401);
                 return;
             }
         }
         $context = new RequestContext($request->getPath(), $request->getMethod());
         $matcher = new UrlMatcher($routes, $context);
         try {
             $parameters = $matcher->match($request->getPath());
             $action = $parameters['_action'];
             $controller = new HttpController($this->worker, $this, $request, $response);
             call_user_func(array($controller, $action), $parameters);
         } catch (ResourceNotFoundException $e) {
             $response->writeHead(404, array('Content-Type' => 'text/plain'));
             $response->end("Not found\n");
             $this->outputAccessLog($request, 404);
         }
     });
     $this->booted = true;
     $this->output->writeln("<info>Initializing http server:</info> <comment>http://" . $this->host . ":" . $this->port . "/</comment>");
 }
Example #26
0
 /**
  * Create and configure the server objects
  */
 protected function setupServer()
 {
     $this->socketServer = new SocketServer($this->getEventLoop());
     //		$this->socketServer->on('connection', function ($conn) {
     //			/** @var ConnectionInterface $conn */
     //			$this->writeln('rcv');
     //		});
     $httpServer = new HttpServer($this->socketServer, $this->getEventLoop());
     $httpServer->on('request', array($this, 'handle'));
     $this->socketServer->listen($this->port, $this->ip);
     $this->writeln(Constants::MESSAGE_CLI_WELCOME . PHP_EOL);
     $this->writeln('Start listening on %s:%s', $this->ip, $this->port);
 }
 function __construct(ReactSocketServer $socket, MiddlewareAdapter $hub)
 {
     parent::__construct($socket);
     $this->hub = $hub;
     $this->on('request', array($this, 'onRequest'));
 }
Example #28
0
 public function childServer($addr)
 {
     $output = $this->output;
     $bindTo = json_decode($addr, true);
     $this->childHost = $bindTo['host'];
     $this->port = $bindTo['port'];
     cli_set_process_title("mpcmf/console server:run/child -b {$this->childHost} -p {$this->port}");
     posix_setgid(99);
     posix_setuid(99);
     posix_seteuid(99);
     posix_setegid(99);
     $loop = Factory::create();
     $socket = new reactSocketServer($loop);
     $http = new reactHttpServer($socket);
     $http->on('request', function (reactRequest $request, reactResponse $response) use($output) {
         //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> New connection");
         //MPCMF_DEBUG && $clientName = $request->getRemoteAddress() . '#' . spl_object_hash($request);
         //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Client connected");
         profiler::resetStack();
         if (!$this->prepare($request, $response, $output)) {
             return;
         }
         //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Starting application</info>");
         try {
             $app = $this->app();
             $slim = $app->slim();
             $originApplication = $this->applicationInstance->getCurrentApplication();
             $this->applicationInstance->setApplication($app);
             $slim->call();
         } catch (\Exception $e) {
             $response->writeHead(500);
             $response->end("Exception: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}\n{$e->getTraceAsString()}");
             return;
         }
         /** @var int[]|Headers[]|string[] $content */
         $content = $slim->response->finalize();
         Util::serializeCookies($content[1], $slim->response->cookies, $slim->settings);
         $content[1] = $content[1]->all();
         $this->applicationInstance->setApplication($originApplication);
         //MPCMF_DEBUG && $output->writeln("<info>[{$clientName}] Ending application</info>");
         //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> Writing data and closing connection");
         static $serverSoftware;
         if ($serverSoftware === null) {
             $serverSoftware = 'MPCMF Async PHP ' . phpversion();
         }
         if (array_key_exists('HTTP_ACCEPT_ENCODING', $_SERVER) && strpos($_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false) {
             $content[1]['Content-Encoding'] = 'gzip';
             $content[2] = gzencode($content[2], 9);
         }
         $content[1]['X-PHP-Server'] = $serverSoftware;
         $content[1]['X-PHP-Server-Addr'] = "{$this->childHost}:{$this->port}";
         $response->writeHead($content[0], $content[1]);
         $response->end($content[2]);
         //MPCMF_DEBUG && $output->writeln("<info>[CHILD:{$this->port}]</info> Connection closed");
     });
     $output->writeln("<error>[CHILD]</error> Starting child server on {$this->childHost}:{$this->port}");
     $socket->listen($this->port, $this->childHost);
     $loop->run();
 }
define('WEBROOT', __DIR__ . DIRECTORY_SEPARATOR . 'webroot');
use Clue\React\Sse\BufferedChannel;
use GuzzleHttp\Client;
use League\Event\Emitter;
use React\EventLoop\Factory;
use React\Filesystem\Filesystem;
use React\Http\Server as HttpServer;
use React\Socket\Server as SocketServer;
use WyriHaximus\React\Examples\HostnameAnalyzer\Listeners\ChannelListener;
use WyriHaximus\React\Examples\HostnameAnalyzer\Listeners\DnsListener;
use WyriHaximus\React\Examples\HostnameAnalyzer\Listeners\GeoListener;
use WyriHaximus\React\Examples\HostnameAnalyzer\Listeners\TitleListener;
use WyriHaximus\React\Examples\HostnameAnalyzer\ResponseHandler;
use WyriHaximus\React\RingPHP\HttpClientAdapter;
require 'vendor/autoload.php';
$loop = Factory::create();
$socket = new SocketServer($loop);
$http = new HttpServer($socket, $loop);
$filesystem = Filesystem::create($loop);
$dns = (new \React\Dns\Resolver\Factory())->createCached('8.8.8.8', $loop);
$guzzle = new Client(['handler' => new HttpClientAdapter($loop, null, $dns)]);
$channel = new BufferedChannel();
$emitter = new Emitter();
$emitter->useListenerProvider(new TitleListener($emitter, $guzzle));
$emitter->useListenerProvider(new DnsListener($emitter, $dns));
$emitter->useListenerProvider(new GeoListener($emitter, $guzzle));
$emitter->useListenerProvider(new ChannelListener($emitter, $channel));
$files = $filesystem->dir(WEBROOT)->ls();
$http->on('request', new ResponseHandler($files, $filesystem, $emitter, $channel));
$socket->listen(1337);
$loop->run();
Example #30
0
 /** @test */
 public function requestsShouldTriggersGloubsterErrorCallback()
 {
     $exception = new \Exception('This is an exception');
     $reactor = $this->getReactSocketServerMock();
     $server = new HttpServer($reactor);
     $handler = $this->getMessageHandlerMock();
     $handler->expects($this->once())->method('error')->with($this->equalTo($exception));
     $httpListener = new HTTPListener($server, $reactor, $this->getLogger());
     $httpListener->attach($handler);
     $httpListener->listen();
     $request = new \React\Http\Request('GET', '/');
     $response = $this->getReactHttpResponseMock();
     $server->emit('request', array($request, $response));
     $request->emit('error', array($exception));
 }