/** * Handler called when a CONNECT message is sent by a client * * A React SocketClient will be created, Google DNS is used to resolve host names. When the connection is made * several event listeners are attached. When data is received on the stream, it is forwarded to the client requesting * the proxied TCP connection * * Other events forwarded are connect and close * * @param WebSocketTransportInterface $user * @param $message */ protected function requestConnect(WebSocketTransportInterface $user, $message) { $address = $message->address; $this->logger->notice(sprintf("User %s requests connection to %s", $user->getId(), $address)); try { $dnsResolverFactory = new React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached('8.8.8.8', $this->loop); $stream = new \React\SocketClient\Connector($this->loop, $dns); list($host, $port) = explode(":", $address); $logger = $this->logger; $that = $this; $stream->create($host, $port)->then(function (\React\Stream\Stream $stream) use($user, $logger, $message, $address, $that) { $id = uniqid("stream-{$address}-"); $that->addStream($user, $id, $stream); // Notify the user when the connection has been made $user->sendString(json_encode(array('connection' => $id, 'event' => 'connected', 'tag' => property_exists($message, 'tag') ? $message->tag : null))); // Forward data back to the user $stream->on("data", function ($data) use($stream, $id, $user, $logger) { $logger->notice("Forwarding " . strlen($data) . " bytes from stream {$id} to {$user->getId()}"); $message = array('connection' => $id, 'event' => 'data', 'data' => $data); $user->sendString(json_encode($message)); }); // When the stream closes, notify the user $stream->on("close", function () use($user, $id, $logger, $address) { $logger->notice(sprintf("Connection %s of user %s to %s has been closed", $id, $user->getId(), $address)); $message = array('connection' => $id, 'event' => 'close'); $user->sendString(json_encode($message)); }); }); } catch (Exception $e) { $user->sendString(json_encode(array('event' => 'error', 'tag' => property_exists($message, 'tag') ? $message->tag : null, 'message' => $e->getMessage()))); } }
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void Script exit code */ protected function execute(InputInterface $input, OutputInterface $output) { $brainName = $input->getArgument('brain'); $host = $input->getArgument('server'); $brain = $this->brainFactory->build($brainName); $responseInterpreter = new \Connect4\Client\ResponseInterpreter(); $client = new \Connect4\Client\Client($brain); $loop = \React\EventLoop\Factory::create(); $dnsResolverFactory = new \React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop); $connector = new \React\SocketClient\Connector($loop, $dns); $connector->create($host, 1337)->then(function (\React\Stream\Stream $stream) use($brain, $responseInterpreter, $client) { $stream->write($brain->getName()); $stream->on('data', function ($data) use($stream, $client, $responseInterpreter) { if (!$data) { die('CONNECTION TERMINATED'); } $response = $responseInterpreter->buildResponse($data); $move = $client->handle($response); if ($move) { $stream->write($move->getColumn()->getValue()); } }); }); $loop->run(); }
function connectToLightTable($clientId, $port, $projectRootDir, Logger $log) { $message = ['client-id' => intval($clientId), 'tags' => 'php.client', 'commands' => ['editor.eval.php', 'editor.eval.php.exception', 'editor.eval.php.result'], 'name' => 'PHP', 'type' => 'php', 'dir' => $projectRootDir]; $loop = EventLoopFactory::create(); $dnsResolverFactory = new React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop); $connector = new React\SocketClient\Connector($loop, $dns); $connector->create('127.0.0.1', intval($port))->then(function (React\Stream\Stream $stream) use($log, $message) { echo 'Connected'; $encodedMessage = json_encode($message); $stream->write($encodedMessage . "\n"); $log->addInfo(sprintf('Acknowledged connection and client id #%d', $message['client-id'])); $stream->on('data', function ($data) use($stream, $log, $encodedMessage) { $log->addInfo(sprintf('Decoding data "%s"', print_r($data, true))); $decodedData = json_decode($data, $asAssociativeArray = true); if ($decodedData[1] == 'editor.eval.php') { try { ob_start(); require $decodedData[2]['path']; $output = ob_get_contents(); $outputType = 'result'; $responseType = 'editor.eval.php.result'; } catch (\Exception $exception) { $output = $exception->getMessage(); $output .= $exception->getTraceAsString(); $outputType = 'ex'; $responseType = 'editor.eval.php.exception'; } $response = json_encode([$decodedData[0], $responseType, ["meta" => $decodedData[2]['meta'], $outputType => $output]]); $stream->write($response . "\n"); ob_end_clean(); } if ($decodedData[1] === 'client.close') { $stream->close(); } }); }); $loop->run(); }
/** * Execute the console command. * * @return void */ public function fire() { echo 'Iniciado' . PHP_EOL; $start = microtime(true); $totalUsers = User::count(); $buffer = ''; $loop = \React\EventLoop\Factory::create(); $dnsResolverFactory = new \React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop); $connector = new \React\SocketClient\Connector($loop, $dns); $connector->create('127.0.0.1', 1337)->then(function (\React\Stream\Stream $stream) use(&$buffer) { $stream->on('data', function ($data, $stream) use(&$buffer) { $buffer .= $data; }); }); $loop->nextTick(function () use($totalUsers) { $this->users = $this->getUsers($totalUsers / 2, 0); }); $loop->run(); $buffer = unserialize($buffer); $this->users = array_merge($this->users, $buffer); echo 'Processados ' . count($this->users) . ' usuários' . PHP_EOL; echo 'Demorou ' . number_format((microtime(true) - $start) * 1000, 2, ',', '') . 'ms' . PHP_EOL; }
$messages = explode("", $buffer . substr($data, 0, -1)); $buffer = ''; foreach ($messages as $message) { #fwrite(STDERR, colorize($message, 'yellow')." : ".colorize('received from the browser', 'green')."\n"); $msg = json_decode($message); if (isset($msg)) { if ($msg->func == 'message' && $msg->body != '') { $msg = $msg->body; } elseif ($msg->func == 'unregister') { \Moxl\Stanza\Stream::end(); } elseif ($msg->func == 'register') { $cd = new \Modl\ConfigDAO(); $config = $cd->get(); $domain = \Moxl\Utils::getDomain($msg->host); #fwrite(STDERR, colorize('open a socket to '.$domain, 'yellow')." : ".colorize('sent to XMPP', 'green')."\n"); $connector->create($domain, 5222)->then($xmpp_behaviour); } } else { return; } $rpc = new \RPC(); $rpc->handle_json($msg); $msg = json_encode(\RPC::commit()); \RPC::clear(); if (!empty($msg)) { echo base64_encode(gzcompress($msg, 9)) . ""; #fwrite(STDERR, colorize($msg, 'yellow')." : ".colorize('sent to the browser', 'green')."\n"); } $xml = \Moxl\API::commit(); \Moxl\API::clear(); $loop->tick();
$msg = $msg->body; } elseif ($msg->func == 'unregister') { \Moxl\Stanza\Stream::end(); } elseif ($msg->func == 'register') { $cd = new \Modl\ConfigDAO(); $config = $cd->get(); $port = 5222; $dns = \Moxl\Utils::resolveHost($msg->host); if (isset($dns->target) && $dns->target != null) { $msg->host = $dns->target; } if (isset($dns->port) && $dns->port != null) { $port = $dns->port; } #fwrite(STDERR, colorize('open a socket to '.$domain, 'yellow')." : ".colorize('sent to XMPP', 'green')."\n"); $connector->create($msg->host, $port)->then($xmpp_behaviour); } } else { return; } $rpc = new \RPC(); $rpc->handle_json($msg); $msg = \RPC::commit(); \RPC::clear(); if (!empty($msg)) { //echo json_encode($msg).""; echo base64_encode(gzcompress(json_encode($msg), 9)) . ""; //fwrite(STDERR, colorize(json_encode($msg), 'yellow')." : ".colorize('sent to the browser', 'green')."\n"); } $xml = \Moxl\API::commit(); \Moxl\API::clear();
<?php /** * @author Jenner <*****@*****.**> * @license https://opensource.org/licenses/MIT MIT * @datetime: 2015/11/13 20:21 */ require dirname(__DIR__) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php'; $loop = React\EventLoop\Factory::create(); $dnsResolverFactory = new React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop); $connector = new React\SocketClient\Connector($loop, $dns); for ($i = 0; $i < 10; $i++) { $connector->create('127.0.0.1', 4020)->then(function (React\Stream\Stream $stream) use($loop) { $stream->write("GET /reactphp/event-loop/blob/master/src/LibEventLoop.php HTTP/1.1\nHost: github.com\nConnection: keep-alive\nCache-Control: max-age=0\r\n\r\n"); $stream->end(); $stream->on('data', function ($data) use($stream) { echo $data; }); }); } $loop->run();
<?php require_once 'vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $dnsResolverFactory = new React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop); $connector = new React\SocketClient\Connector($loop, $dns); file_put_contents('log', print_r($argv, TRUE)); $port = $argv[1]; $client_id = $argv[2]; $client = ['name' => 'php-client', 'client-id' => $client_id, 'dir' => getcwd(), 'commands' => ['editor.eval.php'], 'type' => 'php']; file_put_contents('log', print_r($client, TRUE), FILE_APPEND); $connector->create('127.0.0.1', $port)->then(function (React\Stream\Stream $stream) { file_put_contents('log', 'Connected and stuff', FILE_APPEND); $stream->write('Connected'); $stream->write(json_encode($client)); $stream->on('data', function ($data) use($stream) { file_put_contents('log', print_r($data, TRUE), FILE_APPEND); }); $stream->close(); }); /* $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $socket->on('connection', function ($c) { $c->write("Hello LT!\n"); $c->on('data', function ($data) use ($c) { $c->close(); });
<?php require_once '../vendor/autoload.php'; /** Example is used with React stream, but you can use whatever library you want to as long as it implement Madkom\EventStore\Client\Domain\Socket\Stream Your EventStore must be up, to handle connection */ $loop = React\EventLoop\Factory::create(); $dnsResolverFactory = new React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached(null, $loop); $connector = new React\SocketClient\Connector($loop, $dns); $resolvedConnection = $connector->create('127.0.0.1', 1113); $resolvedConnection->then(function (React\Stream\Stream $stream) { // We create Event Store API Object $eventStore = new \Madkom\EventStore\Client\Application\Api\EventStore(new \Madkom\EventStore\Client\Infrastructure\ReactStream($stream), new \Madkom\EventStore\Client\Infrastructure\InMemoryLogger()); // We add bunch of listeners, because API is asynchronous $eventStore->addAction(\Madkom\EventStore\Client\Domain\Socket\Message\MessageType::HEARTBEAT_REQUEST, function () { echo "I response to ES heartbeat request\n"; }); $eventStore->addAction(\Madkom\EventStore\Client\Domain\Socket\Message\MessageType::WRITE_EVENTS_COMPLETED, function ($data) { echo "Added new event: \n"; // print_r($data); }); $eventStore->addAction(\Madkom\EventStore\Client\Domain\Socket\Message\MessageType::READ_STREAM_EVENTS_FORWARD_COMPLETED, function ($data) { print_r($data); }); //We start to listen for event we added $eventStore->run(); //Now let's try writing messages to stream $eventStreamId = 'someteststream'; // Add new event to stream