예제 #1
0
 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();
 }
예제 #2
0
 public function __construct(LoopInterface $loop)
 {
     $context = new \React\ZMQ\Context($loop);
     $pusher = new Pusher();
     $workers = $context->getSocket(\ZMQ::SOCKET_PUSH);
     $workers->bind("tcp://127.0.0.1:5557");
     // Listen for work from the web
     $receiver = $context->getSocket(\ZMQ::SOCKET_PULL);
     $receiver->bind("tcp://127.0.0.1:5555");
     $receiver->on('message', function ($msg) use($workers) {
         // Create
         echo "Received: " . $msg . "\n";
         $workers->send($msg);
     });
     $control = $context->getSocket(\ZMQ::SOCKET_PULL);
     $control->bind('tcp://127.0.0.1:5510');
     $control->on('message', function ($msg) use($pusher) {
         echo "CONTROL MESSAGE\n";
         $arr = json_decode($msg, true);
         $slug = $arr['slug'];
         $req = $arr['req'];
         $pusher->send($slug, $arr['req']);
     });
     $listener = $context->getSocket(\ZMQ::SOCKET_PULL);
     $listener->bind('tcp://127.0.0.1:5559');
     $listener->on('message', function ($msg) use($pusher) {
         echo " + - - - - - - - - - + \n";
         echo "       RESULTS         \n";
         print_r($msg);
         $message = json_decode($msg, true);
         if ($message['command'] == 'client.gotRequest') {
             $pusher->onClientGotRequest($message['slug']);
         } else {
             if ($message['command'] == 'client.gotPayment') {
                 $pusher->onClientGotPayment($message['slug']);
             } else {
                 if ($message['command'] == 'tx.complete') {
                     try {
                         $request = Request::find(['slug' => $message['slug']]);
                         $transaction = TransactionFactory::fromHex($message['tx']);
                         Transaction::create(['transaction' => $message['tx'], 'request_id' => $request->id, 'txid' => $transaction->getTransactionId()]);
                         $pusher->onCompleteTx($message['slug'], $message['tx']);
                     } catch (\Exception $e) {
                         return;
                     }
                 } else {
                     if ($message['command'] == 'tx.partial') {
                         $pusher->onCompleteTx($message['slug'], $message['tx']);
                     }
                 }
             }
         }
         echo "\n + - - - - - - - - - + \n\n";
     });
     // Set up our WebSocket server for clients wanting real-time updates
     $webSock = new \React\Socket\Server($loop);
     $webSock->listen(8080, '0.0.0.0');
     // Binding to 0.0.0.0 means remotes can connect
     $webServer = new \Ratchet\Server\IoServer(new \Ratchet\Http\HttpServer(new \Ratchet\WebSocket\WsServer(new \Ratchet\Wamp\WampServer($pusher))), $webSock);
 }
예제 #3
0
파일: Server.php 프로젝트: frosty22/ratchet
 /**
  * Run IO server
  */
 public function run()
 {
     $wsServer = new \Ratchet\WebSocket\WsServer($this->application);
     $httpServer = new \Ratchet\Http\HttpServer($wsServer);
     $socket = new \React\Socket\Server($this->loop);
     $socket->listen($this->port, $this->server);
     $server = new \Ratchet\Server\IoServer($httpServer, $socket, $this->loop);
     $server->run();
 }
예제 #4
0
 public function run()
 {
     if (!isset($this->params['token'])) {
         throw new \Exception('A token must be set. Please see https://my.slack.com/services/new/bot');
     }
     $this->loadInternalCommands();
     $this->init();
     $logger = new \Zend\Log\Logger();
     $writer = new \Zend\Log\Writer\Stream("php://output");
     $logger->addWriter($writer);
     $loop = \React\EventLoop\Factory::create();
     $client = new \Devristo\Phpws\Client\WebSocket($this->wsUrl, $loop, $logger);
     $client->on("request", function ($headers) use($logger) {
         $logger->notice("Request object created!");
     });
     $client->on("handshake", function () use($logger) {
         $logger->notice("Handshake received!");
     });
     $client->on("connect", function () use($logger, $client) {
         $logger->notice("Connected!");
     });
     $client->on("message", function ($message) use($client, $logger) {
         $data = $message->getData();
         $logger->notice("Got message: " . $data);
         $data = json_decode($data, true);
         $command = $this->getCommand($data);
         if ($command instanceof Command\BaseCommand) {
             $command->setClient($client);
             $command->setChannel($data['channel']);
             $command->setUser($data['user']);
             $command->setContext($this->context);
             $command->executeCommand($data, $this->context);
         }
     });
     $client->open();
     /* Webserver */
     if ($this->webserverPort !== false) {
         $logger->notice("Listening on port " . $this->webserverPort);
         $socket = new \React\Socket\Server($loop);
         $http = new \React\Http\Server($socket);
         $http->on('request', function ($request, $response) use($client) {
             $post = $request->getPost();
             if ($post['name'] == 'output') {
                 $hook = new \PhpSlackBot\Webhook\OutputWebhook();
                 $hook->setClient($client);
                 $hook->setContext($this->context);
                 $hook->executeWebhook(json_decode($post['payload'], true));
             }
             $response->writeHead(200, array('Content-Type' => 'text/plain'));
             $response->end("Ok\n");
         });
         $socket->listen(8080);
     }
     $loop->run();
 }
예제 #5
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $port = intval($this->option('port'));
     $loop = \React\EventLoop\Factory::create();
     $pusher = new \App\Websocket\Pusher($loop);
     $webSock = new \React\Socket\Server($loop);
     $webSock->listen($port, '0.0.0.0');
     $webServer = new \Ratchet\Server\IoServer(new \Ratchet\Http\HttpServer(new \Ratchet\WebSocket\WsServer(new \App\Websocket\Chat($pusher))), $webSock);
     \App\Websocket\Log::v(' ', $loop, "Starting Websocket Service on port " . $port);
     $loop->run();
 }
예제 #6
0
 /**
  * Running HTTP Server
  */
 public function run()
 {
     $loop = new \React\EventLoop\StreamSelectLoop();
     $socket = new \React\Socket\Server($loop);
     $http = new \React\Http\Server($socket, $loop);
     $http->on('request', function ($request, $response) {
         with(new HttpSession($this->host, $this->port, $this->verbose))->handle($request, $response);
     });
     $socket->listen($this->port, $this->host);
     $loop->run();
 }
 /**
  * Execute the console command.
  *
  * @return void
  */
 public function fire()
 {
     echo 'Iniciando servidor...' . PHP_EOL;
     $totalUsers = User::count();
     $loop = \React\EventLoop\Factory::create();
     $socket = new \React\Socket\Server($loop);
     $socket->on('connection', function ($conn) use($totalUsers) {
         echo 'Enviando mensagem...' . PHP_EOL;
         $users = $this->getUsers($totalUsers / 2, $totalUsers / 2);
         $conn->end(serialize($users));
         echo 'Enviada' . PHP_EOL;
     });
     $socket->listen(1337);
     $loop->run();
 }
예제 #8
0
 public function actionRun()
 {
     $loop = \React\EventLoop\Factory::create();
     $socket = new \React\Socket\Server($loop);
     $socket->on('connection', function ($conn) {
         $conn->write("Hello there!\n");
         $conn->write("Welcome to this amazing server!\n");
         $conn->write("Here's a tip: don't say anything.\n");
         $conn->on('data', function ($data) use($conn) {
             $conn->close();
         });
     });
     $socket->listen(1337);
     $loop->run();
 }
예제 #9
0
 /**
  * @param int $port
  * @throws \React\Socket\ConnectionException
  */
 public function start($port = 6364)
 {
     $socket = new \React\Socket\Server($this->loop);
     $http = new \React\Http\Server($socket);
     $http->on('request', function (Request $request, Response $response) {
         $path = trim($request->getPath(), '/');
         if (!array_key_exists($path, $this->routes)) {
             $this->response($response, 0, "method not found", 101);
             return null;
         }
         $query_info = $request->getQuery();
         $method = array($this, $this->routes[$path]);
         return call_user_func($method, $query_info, $response);
     });
     $socket->listen($port);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var TableManager $tableManager */
     $tableManager = $this->container['table_manager'];
     /** @var WsServer $webSocketServer */
     $webSocketServer = $this->container['websocket_server'];
     /** @var Server $socketServer */
     $socketServer = $this->container['socket_server'];
     /** @var LoopInterface $loop */
     $loop = $this->container['loop'];
     $tableManager->createTable();
     $socket = new \React\Socket\Server($loop);
     $socket->listen($input->getOption('websocket-port'), '0.0.0.0');
     new IoServer(new HttpServer($webSocketServer), $socket, $loop);
     $socketServer->listen($input->getOption('port'));
     $loop->run();
 }
예제 #11
0
 /**
  * Run the Teleport HTTP Server on the specified port.
  * 
  * @param int $port A valid port to run the Teleport HTTP Server on.
  *
  * @throws \RuntimeException If an invalid port is specified.
  */
 public function run($port)
 {
     $port = (int) $port;
     if ($port < 1) {
         throw new \RuntimeException("Invalid port specified for Teleport HTTP Server", E_USER_ERROR);
     }
     /** @var \React\EventLoop\LibEventLoop $loop */
     $loop = \React\EventLoop\Factory::create();
     $socket = new \React\Socket\Server($loop);
     $http = new \React\Http\Server($socket);
     $server =& $this;
     $http->on('request', function ($request, $response) use($server) {
         /** @var \React\Http\Request $request */
         /** @var \React\Http\Response $response */
         $arguments = $request->getQuery();
         $arguments['action'] = trim($request->getPath(), '/');
         $headers = array('Content-Type' => 'text/javascript');
         if (isset($arguments['action']) && !empty($arguments['action']) && strpos($arguments['action'], '.') === false) {
             try {
                 /** @var \Teleport\Request\Request $request */
                 $request = $server->getRequest('Teleport\\Request\\APIRequest');
                 $request->handle($arguments);
                 $results = $request->getResults();
                 $response->writeHead(200, $headers);
                 $response->end(json_encode(array('success' => true, 'message' => $results)));
             } catch (InvalidRequestException $e) {
                 $response->writeHead(400, $headers);
                 $response->end(json_encode(array('success' => false, 'message' => $e->getMessage())));
             } catch (\Exception $e) {
                 $response->writeHead(500, $headers);
                 $response->end(json_encode(array('success' => false, 'message' => $e->getMessage())));
             }
         } else {
             $response->writeHead(400, $headers);
             $response->end(json_encode(array('success' => false, 'message' => 'no valid action was specified')));
         }
     });
     if ($this->getConfig()->get('verbose', null, false) || $this->getConfig()->get('debug', null, false)) {
         echo "teleport server initializing" . PHP_EOL;
     }
     $socket->listen($port);
     if ($this->getConfig()->get('verbose', null, false) || $this->getConfig()->get('debug', null, false)) {
         echo "teleport server listening on port {$port}" . PHP_EOL;
     }
     $loop->run();
 }
예제 #12
0
 /**
  * WebSocket constructor.
  * @param NodeInterface $node
  * @param array $commands
  * @param Container $c
  */
 public function __construct(NodeInterface $node, array $commands, Container $c)
 {
     $loop = $c['loop'];
     $context = $c['zmq'];
     $pusher = new Pusher($node, $commands);
     // Listen for the web server to make a ZeroMQ push after an ajax request
     $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('');
     $pull->on('message', array($pusher, 'onMessage'));
     // Set up our WebSocket server for clients wanting real-time updates
     $webSock = new \React\Socket\Server($loop);
     $webSock->listen(8080, '0.0.0.0');
     // Binding to 0.0.0.0 means remotes can connect
     $this->server = new IoServer(new HttpServer(new WsServer(new WampServer($pusher))), $webSock);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Start socket server');
     $loop = \React\EventLoop\Factory::create();
     $socket = new \React\Socket\Server($loop);
     $socket->on('connection', function ($conn) {
         echo 'New client !' . "\n";
         $conn->write("Hello there!\n");
         $conn->write("Welcome to this server!\n");
         $conn->on('data', function ($data) use($conn) {
             echo $data . "\n";
             $conn->write($data);
         });
     });
     $socket->listen(4001);
     $loop->run();
 }
예제 #14
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $i = 0;
     $app = function ($request, $response) use(&$i, $output) {
         $i++;
         $text = "This is request number {$i}.\n";
         $headers = array('Content-Type' => 'text/plain');
         $output->writeln($text);
         $response->writeHead(200, $headers);
         $response->end($text);
     };
     $loop = \React\EventLoop\Factory::create();
     $socket = new \React\Socket\Server($loop);
     $http = new \React\Http\Server($socket);
     $http->on('request', $app);
     $socket->listen(1337);
     $loop->run();
 }
예제 #15
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $loop = \React\EventLoop\Factory::create();
     $pusher = new DebugPusher();
     // 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('');
     $pull->on('message', array($pusher, 'onMessage'));
     // Set up our WebSocket server for clients wanting real-time updates
     $webSock = new \React\Socket\Server($loop);
     $webSock->listen(8080, '0.0.0.0');
     // Binding to 0.0.0.0 means remotes can connect
     new IoServer(new HttpServer(new WsServer(new WampServer($pusher))), $webSock);
     $loop->run();
     return 0;
 }
예제 #16
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $loop = React\EventLoop\Factory::create();
     $pusher = new LowEndPing\Pusher();
     $zmq_host = Config::get('lowendping.websocket.zeromq.host', '127.0.0.1') . ':' . Config::get('lowendping.websocket.zeromq.port', 5555);
     // Listen for the web server to make a ZeroMQ push after a response
     $context = new React\ZMQ\Context($loop);
     $pull = $context->getSocket(ZMQ::SOCKET_PULL);
     $this->info('Binding ZMQ to ' . $zmq_host);
     $pull->bind('tcp://' . $zmq_host);
     // Binding to 127.0.0.1 means the only client that can connect is itself
     $pull->on('message', array($pusher, 'onServerResponse'));
     $this->info('Binding Ratchet Websocket to 0.0.0.0:' . Config::get('lowendping.websocket.port', 8080));
     // Set up our WebSocket server for clients wanting real-time updates
     $webSock = new React\Socket\Server($loop);
     $webSock->listen(Config::get('lowendping.websocket.port', 8080), '0.0.0.0');
     // Binding to 0.0.0.0 means remotes can connect
     $webServer = new Ratchet\Server\IoServer(new Ratchet\Http\HttpServer(new Ratchet\WebSocket\WsServer(new Ratchet\Wamp\WampServer($pusher))), $webSock);
     $loop->run();
 }
예제 #17
0
 public function start(Output\OutputInterface $output)
 {
     /* @var $_loop  \React\EventLoop\LoopInterface*/
     $loop = \React\EventLoop\Factory::create();
     // create a new socket
     $socket = new \React\Socket\Server($loop);
     // pipe a connection into itself
     $socket->on('connection', function (\React\Socket\Connection $conn) use($output) {
         $output->writeln('CONNECTION ESTABLISHED: ' . $conn->getRemoteAddress());
         $conn->pipe($conn);
         $conn->on('data', function ($data) use($conn, $output) {
             $conn->write('some additional information from data-event-handler ...');
             $output->writeln("Server received: {$data}");
         });
     });
     echo "Socket server listening on port 4000.\n";
     echo "You can connect to it by running: telnet localhost 4000\n";
     $socket->listen(4000);
     $loop->run();
 }
예제 #18
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     //Init rena
     $app = MiraApp::getInstance();
     // Setup the react event loop and call up the pusher class
     $loop = \React\EventLoop\Factory::create();
     $pusher = new Pusher();
     $stomper = new stompSend();
     // ZeroMQ server
     $context = new \React\ZMQ\Context($loop);
     $pull = $context->getSocket(ZMQ::SOCKET_PULL);
     $pull->bind("tcp://127.0.0.1:5555");
     $pull->on("message", array($pusher, "onMessage"));
     $pull->on("message", array($stomper, "onMessage"));
     // Websocket server
     $webSock = new \React\Socket\Server($loop);
     $webSock->listen(8800, "0.0.0.0");
     $webServer = new \Ratchet\Server\IoServer(new \Ratchet\Http\HttpServer(new \Ratchet\WebSocket\WsServer(new \Ratchet\Wamp\WampServer($pusher))), $webSock);
     $loop->run();
 }
예제 #19
0
 public function start(Output\OutputInterface $output)
 {
     /* @var $_loop  \React\EventLoop\LoopInterface*/
     $loop = \React\EventLoop\Factory::create();
     // create a new socket
     $socket = new \React\Socket\Server($loop);
     // pipe a connection into itself
     $socket->on('connection', function (\React\Socket\Connection $conn) use($output, $loop) {
         $output->writeln('CONNECTION ESTABLISHED: ' . $conn->getRemoteAddress());
         //$infiniteStreamHandle	= fopen('/tmp/random', 'r');
         $infiniteStreamHandle = fopen('/dev/urandom', 'r');
         $fileToStream = new \React\Stream\Stream($infiniteStreamHandle, $loop);
         $output->writeln('streaming ...');
         //$conn->pipe($infiniteStreamHandle);
         $fileToStream->pipe($conn);
     });
     echo "Socket server listening on port 4000.\n";
     echo "You can connect to it by running: telnet localhost 4000\n";
     $socket->listen(4000);
     $loop->run();
 }
예제 #20
0
 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)));
 }
예제 #21
0
 /**
  * @param $port
  *
  * @throws \React\Socket\ConnectionException
  */
 public function listen($port = false)
 {
     if ($port) {
         $this->port = $port;
     }
     /**
      * @param \React\Http\Request $request
      * @param \React\Http\Response $response
      */
     $requestHandler = function ($request, $response) {
         // If debugging is on, track the request start time
         $requestStartTime = $this->debugging ? microtime(true) : null;
         $symfonyFormattedRequest = $this->convertRequest($request);
         // Run the Lumen app and get a response
         /** @var \Illuminate\Http\Response $lumenResponse */
         $lumenResponse = $this->lumenApplication->dispatch($symfonyFormattedRequest);
         $lumenResponse->prepare($symfonyFormattedRequest);
         // Build a React response from the symfony response
         $response->writeHead($lumenResponse->getStatusCode(), $lumenResponse->headers->all());
         $response->end($lumenResponse->content());
         if ($this->debugging) {
             echo $this->getLogEntry($request, $lumenResponse, $requestStartTime);
         }
         $response->on('close', function () use($lumenResponse) {
             $this->lumenApplication->runTerminableMiddleware($lumenResponse);
         });
     };
     $loop = \React\EventLoop\Factory::create();
     $socket = new \React\Socket\Server($loop);
     $http = new \React\Http\Server($socket, $loop);
     $http->on('request', $requestHandler);
     if ($this->debugging) {
         echo "Server running on port " . $this->port . PHP_EOL . PHP_EOL;
     }
     $socket->listen($this->port);
     $loop->run();
 }
예제 #22
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $timer = new \Svengerlach\Flake\Timer();
     $sequencer = new \Svengerlach\Flake\Sequencer();
     $generator = new \Svengerlach\Flake\Generator($timer, $sequencer, $input->getOption('epoch-start'), $input->getOption('node-identifier'));
     $loop = \React\EventLoop\Factory::create();
     $socket = new \React\Socket\Server($loop);
     $socket->on('connection', function (\React\Socket\Connection $conn) use($generator) {
         $conn->on('data', function ($data) use($conn, $generator) {
             $data = trim($data);
             if (0 !== strpos($data, 'GET ')) {
                 return $conn->close();
             }
             $parameter = substr($data, 4);
             for ($i = 0; $i < (int) $parameter; $i++) {
                 $flake = $generator->generate();
                 $conn->write($flake . "\n");
             }
             $conn->end();
         });
     });
     $socket->listen($input->getOption('port'), $input->getOption('ip'));
     $loop->run();
 }
예제 #23
0
 function run()
 {
     $this->before();
     $port = $this->setting['port'];
     Load::file(MAIN_DIR . DS . 'vendor' . DS . 'autoload.php');
     $loop = React\EventLoop\Factory::create();
     $socket = new React\Socket\Server($loop);
     $conns = new \SplObjectStorage();
     $this->connectionList =& $conns;
     $socket->on('connection', function ($conn) use($conns) {
         $this->onConnection($conn);
         $conns->attach($conn);
         $this->console('Attach new connection.');
         $conn->on('data', function ($data) use($conns, $conn) {
             $this->onMessage($conn, $data);
             //                foreach ($conns as $current) {
             //                    if ($conn !== $current) {
             //                        continue;
             //                    }
             //
             //                    $this->onMessage($conn, $data);
             //                }
         });
         $conn->on('end', function () use($conns, $conn) {
             $this->onClose($conn);
             $this->console('Detach connection.');
             $conns->detach($conn);
         });
     });
     $this->console('Socket server listening on port ' . $port);
     $socket->listen($port);
     $loop->addPeriodicTimer($this->setting['timer'], function ($timer) use($conns) {
         $this->onTick($timer);
     });
     $loop->run();
 }
예제 #24
0
파일: Provider.php 프로젝트: jgswift/qtcp
 function __construct(qtcp\Application $application)
 {
     $this->application = $application;
     $loop = \React\EventLoop\Factory::create();
     $loop->addPeriodicTimer($application->clock->getSpeed(), function () {
         $this->application->clock->tick();
         $clients = $this->application->getServer()->getClients();
         // INCREASE IDLE TIME ON ALL CLIENTS
         if (!empty($clients)) {
             foreach ($clients as $client) {
                 $client->idle();
                 //KICK CLIENTS IDLING OVER 15 MINUTES
                 if ($client->isIdle()) {
                     $client->close();
                 }
             }
         }
     });
     $component = new HttpServer(new WsServer($this->server = new \qtcp\Server($application)));
     $socket = new \React\Socket\Server($loop);
     $resource = $application->getResource();
     $socket->listen($resource->getPort(), $resource->getPath());
     $this->io = new IoServer($component, $socket, $loop);
 }
예제 #25
0
파일: Main.php 프로젝트: catterer/stuff
function main()
{
    $loop = React\EventLoop\Factory::create();
    $socket = new React\Socket\Server($loop);
    $http = new React\Http\Server($socket, $loop);
    $st = new Storage('im.db');
    $http->on('request', function ($request, $response) use($st) {
        $r = new Request($request, $response);
        #       var_dump($r->request->getHeaders());
        if (!array_key_exists("Content-Length", $r->request->getHeaders())) {
            $r->abort(400, "need json content");
            return;
        }
        $r->contentLength = intval($r->request->getHeaders()["Content-Length"]);
        $request->on('data', function ($data) use($r, $st) {
            $r->addInput($data);
            if (!$r->readyToProcess()) {
                return;
            }
            if (!($js = $r->parseInput())) {
                $r->abort(400, "Invalid json");
                return;
            }
            global $methods;
            // imported it from Methods.php.
            // Failed to find how to import it explicitly
            // (like python's "import Variable from Module")
            if (!isset($js->method) || !array_key_exists($js->method, $methods)) {
                $r->abort(400, "Invalid method");
                return;
            }
            try {
                $methods[$js->method]($r, $js, $st);
            } catch (Exception $e) {
                $r->abort(500, "inernal server error");
            }
        });
    });
    echo "Server running at http://127.0.0.1:1337\n";
    $socket->listen(1337);
    $loop->run();
}
예제 #26
0
<?php

include_once __DIR__ . '/../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$dnsResolverFactory = new React\Dns\Resolver\Factory();
$dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);
$socket = new React\Socket\Server($loop);
$socket->listen('9050', 'localhost');
$factory = new Socks\Factory($loop, $dns);
$server = $factory->createServer($socket);
$server->setAuthArray(array('tom' => 'god', 'user' => 'p@ssw0rd'));
echo 'SOCKS server listening on localhost:9050' . PHP_EOL;
$loop->run();
예제 #27
0
<?php

require dirname(dirname(dirname(__DIR__))) . '/vendor/autoload.php';
$loop = new React\EventLoop\StreamSelectLoop();
$sock = new React\Socket\Server($loop);
$app = new Ratchet\Http\HttpServer(new Ratchet\WebSocket\WsServer(new Ratchet\Server\EchoServer()));
$port = $argc > 1 ? $argv[1] : 8000;
$sock->listen($port, '0.0.0.0');
$server = new Ratchet\Server\IoServer($app, $sock, $loop);
$server->run();
예제 #28
0
 /**
  * @param BoardFactory $boardFactory
  *
  * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
  * @throws \React\Socket\ConnectionException
  */
 public function run(BoardFactory $boardFactory)
 {
     $emitter = new Emitter();
     $wamp = new WampConnector($emitter);
     $webSocket = new \React\Socket\Server($this->eventLoop);
     $webSocket->listen(self::SOCKET_LISTEN_PORT, '0.0.0.0');
     $board = $boardFactory->initialize();
     new IoServer(new HttpServer(new WsServer(new WampServer($wamp))), $webSocket);
     $emitter->addListener(QuestionSubscriptionEvent::class, function (QuestionSubscriptionEvent $event) use($wamp, $board) {
         $wamp->onQuestionSubscribe($board->getCategories(), $event->getSessionId());
     });
     $emitter->addListener(ContestantScoreSubscriptionEvent::class, function (ContestantScoreSubscriptionEvent $event) use($wamp, $board) {
         $wamp->onContestantScoreSubscription($board->getContestants(), $event->getSessionId());
     });
     $emitter->addListener(BuzzerStatusSubscriptionEvent::class, function (BuzzerStatusSubscriptionEvent $event) use($wamp, $board) {
         $wamp->onBuzzerStatusChange($board->getBuzzerStatus(), [], [$event->getSessionId()]);
     });
     $emitter->addListener(BuzzerResolutionEvent::class, function (BuzzerResolutionEvent $event) use($wamp) {
         //TODO Store this event
         echo 'Buzzer Resolution: ' . $event->getResolution()->getContestant()->getName() . " buzzed in ({$event->getResolution()->getTime()}ms)\n";
         $wamp->onBuzzerResolution($event->getResolution());
     });
     $emitter->addListener(QuestionAnswerEvent::class, function (QuestionAnswerEvent $event) use($wamp, $board, $emitter) {
         try {
             $questionAnswer = $event->getQuestionAnswer();
             $board->addScore($questionAnswer->getContestant(), $questionAnswer->getRealValue());
             $wamp->onQuestionAnswer($questionAnswer);
         } catch (ContestantNotFoundException $exception) {
             echo $exception->getMessage();
             // TODO handle exception
         }
         if ($questionAnswer->isCorrect()) {
             $emitter->emit(new QuestionDismissalEvent(new QuestionDismissal($questionAnswer->getCategory(), $questionAnswer->getValue())));
             return;
         }
         $emitter->emit(new BuzzerStatusChangeEvent(new BuzzerStatus(true)));
     });
     $emitter->addListener(QuestionDisplayRequestEvent::class, function (QuestionDisplayRequestEvent $event) use($wamp, $board) {
         try {
             $question = $board->getQuestionByCategoryAndValue($event->getCategoryName(), $event->getValue());
             $question->setUsed();
             $wamp->onQuestionDisplay($question, $event->getCategoryName());
         } catch (QuestionNotFoundException $exception) {
             //TODO log this somewhere.
             echo "Error occured, could not find question in category: {$event->getCategoryName()} valued at: {$event->getValue()}";
         }
     });
     $emitter->addListener(DailyDoubleBetEvent::class, function (DailyDoubleBetEvent $event) use($wamp, $board) {
         try {
             $question = $board->getQuestionByCategoryAndValue($event->getCategory(), $event->getValue());
         } catch (QuestionNotFoundException $e) {
             // TODO
         }
         $wamp->onDailyDoubleBetRecieved($question, $event->getCategory(), $event->getBet());
     });
     $emitter->addListener(QuestionDismissalEvent::class, function (QuestionDismissalEvent $event) use($wamp, $board) {
         $dismissal = $event->getDismissal();
         $wamp->onQuestionDismiss($dismissal);
     });
     $emitter->addListener(BuzzReceivedEvent::class, function (BuzzReceivedEvent $event) use($board, $emitter) {
         if (!$board->getBuzzerStatus()->isActive()) {
             // The buzzer isn't active, so there's nothing to do.
             return;
         }
         if ($board->getResolver()->isEmpty()) {
             // If this is the first buzz, then we want to resolve it after the timeout.
             $this->eventLoop->addTimer($this->buzzer_resolve_timeout, function () use($board, $emitter) {
                 $resolution = $board->resolveBuzzes();
                 $emitter->emit(new BuzzerResolutionEvent($resolution));
             });
         }
         // TODO store this event
         echo 'Buzz in (' . $event->getContestant()->getName() . '): ' . $event->getDifference() . "ms \n";
         $board->getResolver()->addBuzz($event);
     });
     $emitter->addListener(BuzzerStatusChangeEvent::class, function (BuzzerStatusChangeEvent $event) use($wamp, $board) {
         $board->setBuzzerStatus($event->getBuzzerStatus());
         $wamp->onBuzzerStatusChange($event->getBuzzerStatus());
     });
     $emitter->addListener(FinalJeopardyCategoryRequest::class, function (FinalJeopardyCategoryRequest $event) use($wamp, $board) {
         $wamp->onFinalJeopardyRequest('category', $board->getFinalJeopardyClue());
     });
     $emitter->addListener(FinalJeopardyClueRequest::class, function (FinalJeopardyClueRequest $event) use($wamp, $board) {
         $wamp->onFinalJeopardyBetCollectionRequest();
         // We're going to wait for a set time
         //TODO this doesn't work for some reason in every case, so we simply don't close the acceptance of responses.
         $this->eventLoop->addTimer($this->final_jeopardy_collection_timeout, function () use($wamp, $board) {
             if (!$board->getFinalJeopardy()->hasAllBets()) {
                 //TODO logging
                 echo "Did not recieve all bets.\n";
                 $missingbets = $board->getFinalJeopardy()->getMissingBets();
                 $missingbets = implode(', ', $missingbets);
                 echo "Require bets from: {$missingbets}\n";
             }
             $wamp->onFinalJeopardyRequest('clue', $board->getFinalJeopardyClue());
         });
     });
     $emitter->addListener(ContestantScoreChangeEvent::class, function (ContestantScoreChangeEvent $event) use($wamp, $board) {
         try {
             $board->addScore(new Contestant($event->getContestant()), $event->getScoreChange());
         } catch (ContestantNotFoundException $e) {
             //TODO
         }
         $contestant = $board->getContestants()->first(function ($key, Contestant $contestant) use($event) {
             return $contestant->getName() === $event->getContestant();
         });
         $wamp->onContestantScoreUpdate($contestant);
     });
     $emitter->addListener(FinalJeopardyBetEvent::class, function (FinalJeopardyBetEvent $event) use($wamp, $board) {
         $finalJeopardy = $board->getFinalJeopardy();
         $finalJeopardy->setBet($event->getContestant(), $event->getBet());
     });
     $emitter->addListener(FinalJeopardyAnswerRequest::class, function (FinalJeopardyAnswerRequest $event) use($wamp, $board) {
         $wamp->onFinalJeopardyAnswerCollectionRequest();
         $this->eventLoop->addTimer($this->final_jeopardy_collection_timeout, function () use($wamp, $board) {
             if (!$board->getFinalJeopardy()->hasAllAnswers()) {
                 //TODO logging
                 echo "Did not receive all final jeopardy answers!\n";
                 $missingAnswers = $board->getFinalJeopardy()->getMissingAnswers();
                 $missingAnswers = implode(', ', $missingAnswers);
                 echo "Require answers from: {$missingAnswers}\n";
             }
             $wamp->onFinalJeopardyRequest('answer', $board->getFinalJeopardyClue());
         });
     });
     $emitter->addListener(FinalJeopardyAnswerEvent::class, function (FinalJeopardyAnswerEvent $event) use($wamp, $board) {
         $finalJeopardy = $board->getFinalJeopardy();
         if ($finalJeopardy->hasAnswer($event->getContestant())) {
             //TODO logging
             echo "{$event->getContestant()} has already submitted a final answer";
             return;
         }
         $finalJeopardy->setAnswer($event->getContestant(), $event->getAnswer());
     });
     $emitter->addListener(FinalJeopardyResponseRequest::class, function (FinalJeopardyResponseRequest $event) use($wamp, $board) {
         $finalJeopardy = $board->getFinalJeopardy();
         if (!$finalJeopardy->hasAnswer($event->getContestant())) {
             //TODO logging
             $response = new FinalJeopardyQuestionResponse($event->getContestant(), 0, 'No answer, Troy');
             $wamp->onFinalJeopardyResponse($response);
             return;
         }
         $wamp->onFinalJeopardyResponse($finalJeopardy->getResponse($event->getContestant()));
     });
     $this->eventLoop->run();
 }
예제 #29
0
<?php

// pipe a connection into itself
require __DIR__ . '/../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$socket->on('connection', function ($conn) {
    $conn->pipe($conn);
});
echo "Socket server listening on port 4000.\n";
echo "You can connect to it by running: telnet localhost 4000\n";
$socket->listen(4000);
$loop->run();
예제 #30
0
<?php

require_once realpath('../../') . '/vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$client = new Predis\Async\Client('tcp://127.0.0.1:6379', $loop);
$socket = new React\Socket\Server($loop);
$http = new React\Http\Server($socket, $loop);
$session_store = new Phluid\Middleware\Sessions\PredisStore($client);
$app = new Phluid\App();
$app->inject(new Phluid\Middleware\Cookies());
$app->inject(new Phluid\Middleware\Sessions(array('store' => $session_store, 'secret' => 'aslkji339jkcmas0o329insdlsdoisdf0s09jasfd')));
$app->get('/', function ($req, $res) {
    if ($count = $req->session['counter']) {
        $count++;
    } else {
        $count = 1;
    }
    $req->session['counter'] = $count;
    $res->renderText("Hello world ;): {$count}");
});
$app->createServer($http);
$socket->listen(4000);
$loop->run();