예제 #1
0
 public function loadEtcResolvConf($filename)
 {
     if (!file_exists($filename)) {
         return When::reject(new \InvalidArgumentException("The filename for /etc/resolv.conf given does not exist: {$filename}"));
     }
     try {
         $deferred = new Deferred();
         $fd = fopen($filename, 'r');
         stream_set_blocking($fd, 0);
         $contents = '';
         $stream = new Stream($fd, $this->loop);
         $stream->on('data', function ($data) use(&$contents) {
             $contents .= $data;
         });
         $stream->on('end', function () use(&$contents, $deferred) {
             $deferred->resolve($contents);
         });
         $stream->on('error', function ($error) use($deferred) {
             $deferred->reject($error);
         });
         return $deferred->promise();
     } catch (\Exception $e) {
         return When::reject($e);
     }
 }
예제 #2
0
 public function __construct(Stream $stream, ParserInterface $parser = null, SerializerInterface $serializer = null)
 {
     if ($parser === null || $serializer === null) {
         $factory = new ProtocolFactory();
         if ($parser === null) {
             $parser = $factory->createResponseParser();
         }
         if ($serializer === null) {
             $serializer = $factory->createSerializer();
         }
     }
     $that = $this;
     $stream->on('data', function ($chunk) use($parser, $that) {
         try {
             $models = $parser->pushIncoming($chunk);
         } catch (ParserException $error) {
             $that->emit('error', array($error));
             $that->close();
             return;
         }
         foreach ($models as $data) {
             try {
                 $that->handleMessage($data);
             } catch (UnderflowException $error) {
                 $that->emit('error', array($error));
                 $that->close();
                 return;
             }
         }
     });
     $stream->on('close', array($this, 'close'));
     $this->stream = $stream;
     $this->parser = $parser;
     $this->serializer = $serializer;
 }
예제 #3
0
 public function job($parameters)
 {
     $pretty = $this->getQueryParameter("pretty", false);
     if ($pretty) {
         $pretty = true;
     }
     $name = $parameters['name'];
     $method = strtolower($this->request->getMethod());
     $job = $this->worker->job->getJob($name);
     if (!$job) {
         $this->response->writeHead(404, array('Content-Type' => 'text/plain'));
         $this->response->end("Not found\n");
         $this->server->outputAccessLog($this->request, 404);
         return;
     }
     if ($method == 'get') {
         $buffer = null;
         $self = $this;
         $response = $this->response;
         $request = $this->request;
         $stream = new Stream(fopen($job->getInfoFilePath(), 'r'), $this->worker->eventLoop);
         $stream->on('data', function ($data, $stream) use(&$buffer) {
             $buffer .= $data;
         });
         $stream->on('end', function ($stream) use($job, $response, $request, $self, &$buffer, $pretty) {
             $info = json_decode($buffer, true);
             $number = 0;
             if (isset($info["runtime_jobs"])) {
                 $number = count($info["runtime_jobs"]);
             }
             $contents = [];
             $contents['number_of_running_jobs'] = $number;
             $response->writeHead(200, array('Content-Type' => 'application/json; charset=utf-8'));
             if ($pretty) {
                 $output = json_encode($contents, JSON_PRETTY_PRINT);
             } else {
                 $output = json_encode($contents);
             }
             $response->end($output);
             $self->server->outputAccessLog($request, 200);
         });
     } elseif ($method == 'post') {
         $query = $this->request->getQuery();
         $this->worker->job->executeJob($job, true, $query);
         $contents = ["status" => "OK"];
         $this->response->writeHead(200, array('Content-Type' => 'application/json; charset=utf-8'));
         if ($pretty) {
             $output = json_encode($contents, JSON_PRETTY_PRINT);
         } else {
             $output = json_encode($contents);
         }
         $this->response->end($output);
         $this->server->outputAccessLog($this->request, 200);
     } else {
         $this->response->writeHead(400, array('Content-Type' => 'text/plain'));
         $this->response->end("Bad Request\n");
         $this->server->outputAccessLog($this->request, 400);
     }
 }
예제 #4
0
 public function __construct(Stream $stream, $protocol, $version, $code, $reasonPhrase, $headers)
 {
     $this->stream = $stream;
     $this->protocol = $protocol;
     $this->version = $version;
     $this->code = $code;
     $this->reasonPhrase = $reasonPhrase;
     $this->headers = $headers;
     $stream->on('data', array($this, 'handleData'));
     $stream->on('error', array($this, 'handleError'));
     $stream->on('end', array($this, 'handleEnd'));
 }
 /**
  * @dataProvider loopProvider
  */
 public function testBufferReadsLargeChunks($condition, $loopFactory)
 {
     if (true !== $condition()) {
         return $this->markTestSkipped('Loop implementation not available');
     }
     $loop = $loopFactory();
     list($sockA, $sockB) = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, 0);
     $streamA = new Stream($sockA, $loop);
     $streamB = new Stream($sockB, $loop);
     $bufferSize = 4096;
     $streamA->bufferSize = $bufferSize;
     $streamB->bufferSize = $bufferSize;
     $testString = str_repeat("*", $streamA->bufferSize + 1);
     $buffer = "";
     $streamB->on('data', function ($data, $streamB) use(&$buffer, &$testString) {
         $buffer .= $data;
     });
     $streamA->write($testString);
     $loop->tick();
     $loop->tick();
     $loop->tick();
     $streamA->close();
     $streamB->close();
     $this->assertEquals($testString, $buffer);
 }
예제 #6
0
 /**
  * @param NetworkAddressInterface $remotePeer
  * @param ConnectionParams $params
  * @return \React\Promise\Promise|\React\Promise\PromiseInterface
  */
 public function outboundHandshake(NetworkAddressInterface $remotePeer, ConnectionParams $params)
 {
     $deferred = new Deferred();
     $awaitVersion = true;
     $this->stream->on('close', function () use(&$awaitVersion, $deferred) {
         if ($awaitVersion) {
             $awaitVersion = false;
             $deferred->reject('peer disconnected');
         }
     });
     $this->on(Message::VERSION, function (Peer $peer, Version $version) use($params) {
         $this->remoteVersion = $version;
         $this->verack();
     });
     $this->on(Message::VERACK, function () use($deferred) {
         if (false === $this->exchangedVersion) {
             $this->exchangedVersion = true;
             $this->emit('ready', [$this]);
             $deferred->resolve($this);
         }
     });
     $this->peerAddress = $remotePeer;
     $this->localVersion = $version = $params->produceVersion($this->msgs, $remotePeer);
     $this->connectionParams = $params;
     $this->send($version);
     return $deferred->promise();
 }
예제 #7
0
 public function subscribe(ObserverInterface $observer, $scheduler = null)
 {
     $this->stream->on('data', function ($data) use($observer) {
         $observer->onNext($data);
     });
     $this->stream->on('error', function ($error) use($observer) {
         $ex = $error instanceof \Exception ? $error : new \Exception($error);
         $observer->onError($ex);
     });
     $this->stream->on('close', function () use($observer) {
         $observer->onCompleted();
     });
     $disposable = parent::subscribe($observer, $scheduler);
     return new BinaryDisposable($disposable, new CallbackDisposable(function () use($observer) {
         $this->removeObserver($observer);
         $this->dispose();
     }));
 }
예제 #8
0
 public function __construct(LoopInterface $loop)
 {
     $bspcProcess = proc_open('pactl subscribe', [['pipe', 'r'], ['pipe', 'w']], $pipes);
     $bspcStdout = new Stream($pipes[1], $loop);
     $bspcStdout->on('data', [$this, 'onUpdate']);
     $loop->addTimer(0, function () {
         $this->queryData();
     });
 }
예제 #9
0
 public function __construct(LoopInterface $loop, SpawnerInterface $spawner, $id, $cmd, $args, $onData, $onExit)
 {
     $this->id = $id;
     $this->loop = $loop;
     $this->process = new Process($spawner->spawn($cmd, $args));
     $this->process->on('exit', function ($exitCode, $termSignal) use($onExit) {
         call_user_func($onExit, $exitCode, $termSignal);
     });
     $this->process->start($loop);
     $this->out = $this->process->stdout;
     $this->in = $this->process->stdin;
     $this->err = $this->process->stderr;
     $this->out->on('data', function ($data) use($onData) {
         call_user_func($onData, $data);
     });
     $this->err->on('data', function ($data) use($onData) {
         call_user_func($onData, $data);
     });
 }
 public function handleRequest($request, $response, $connection)
 {
     $path = $this->getPath($request);
     $fullPath = $this->docroot . DIRECTORY_SEPARATOR . $path;
     echo "Loading static file: {$path}" . PHP_EOL;
     // if(isset($this->fileCache[$path])) {
     //     echo "cache hit for: $path" . PHP_EOL;
     //     $response->setBody($this->fileCache[$path]);
     //     return $this->send($connection, $response);
     // }
     $fd = fopen($fullPath, "r");
     /* @note LibEvent doesn't handle file reads asynchronously (non-blocking) */
     stream_set_blocking($fd, 0);
     $stream = new Stream($fd, $this->loop);
     $this->buffer[$path] = '';
     $stream->on('data', Partial\bind([$this, 'onData'], $path));
     $stream->on('close', Partial\bind([$this, 'onClose'], $path, $response, $connection));
     $stream->on('error', Partial\bind([$this, 'onError'], $path, $response, $connection));
 }
예제 #11
0
 public function __construct(Stream $stream, LoopInterface $loop)
 {
     $this->stream = $stream->stream;
     $this->decorating = $stream;
     $this->loop = $loop;
     $stream->on('error', function ($error) {
         $this->emit('error', [$error, $this]);
     });
     $stream->on('end', function () {
         $this->emit('end', [$this]);
     });
     $stream->on('close', function () {
         $this->emit('close', [$this]);
     });
     $stream->on('drain', function () {
         $this->emit('drain', [$this]);
     });
     $stream->pause();
     $this->resume();
 }
예제 #12
0
 public function probe(Stream $stream, $compression = false, $encryption = false)
 {
     $magic = Protocol::MAGIC;
     if ($compression) {
         $magic |= Protocol::FEATURE_COMPRESSION;
     }
     if ($encryption) {
         $magic |= Protocol::FEATURE_ENCRYPTION;
     }
     $binary = $this->binary;
     $stream->write($binary->writeUInt32($magic));
     // list of supported protocol types (in order of preference)
     $types = array(Protocol::TYPE_DATASTREAM, Protocol::TYPE_LEGACY);
     // last item should get an END marker
     $last = array_pop($types);
     $types[] = $last | Protocol::TYPELIST_END;
     foreach ($types as $type) {
         $stream->write($binary->writeUInt32($type));
     }
     $deferred = new Deferred(function ($resolve, $reject) use($stream) {
         $reject(new \RuntimeException('Cancelled'));
     });
     $buffer = '';
     $fn = function ($data) use(&$buffer, &$fn, $stream, $deferred, $binary) {
         $buffer .= $data;
         if (isset($buffer[4])) {
             $stream->removeListener('data', $fn);
             $deferred->reject(new \UnexpectedValueException('Expected 4 bytes response, received more data, is this a quassel core?', Prober::ERROR_PROTOCOL));
             return;
         }
         if (isset($buffer[3])) {
             $stream->removeListener('data', $fn);
             $deferred->resolve($binary->readUInt32($buffer));
         }
     };
     $stream->on('data', $fn);
     $stream->on('close', function () use($deferred) {
         $deferred->reject(new \RuntimeException('Stream closed, does this (old?) server support probing?', Prober::ERROR_CLOSED));
     });
     return $deferred->promise();
 }
예제 #13
0
파일: Shell.php 프로젝트: bangpound/pecan
 /**
  * @param LoopInterface $loop
  * @throws \LogicException
  */
 public function start(LoopInterface $loop)
 {
     $this->input = new Stream(STDIN, $loop);
     $this->input->on('error', [$this, 'handleError']);
     $this->input->on('data', [$this, 'handleInput']);
     $this->output = new ConsoleOutput($loop);
     $this->output->on('error', [$this, 'handleError']);
     if ($this->isRunning()) {
         throw new \LogicException('The shell is already running.');
     }
     $this->isRunning = true;
     $this->application->setAutoExit(false);
     $this->application->setCatchExceptions(true);
     $this->on('data', function ($command) {
         $ret = $this->application->run(new StringInput($command), $this->output);
         if (0 !== $ret) {
             $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
         }
     });
     $this->on('output', [$this, 'write']);
     $this->emit('running', [$this]);
 }
예제 #14
0
파일: React.php 프로젝트: jahudka/react-mpd
 /**
  * @param Stream $stream
  * @return PromiseInterface
  */
 public function handleInit(Stream $stream)
 {
     $this->stream = $stream;
     return new Promise(function (callable $fulfill, callable $reject) {
         $this->stream->once('data', function ($data) use($fulfill, $reject) {
             if (preg_match('/^ok\\b/i', $data)) {
                 $this->stream->on('data', [$this, 'handleData']);
                 $this->stream->on('error', [$this, 'handleError']);
                 call_user_func($fulfill);
             } else {
                 call_user_func($reject, trim($data));
             }
         });
     });
 }
예제 #15
0
 /**
  * Initializes basic peer functionality - used in server and client contexts
  *
  * @return $this
  */
 private function setupConnection()
 {
     $this->stream->on('data', function ($data) {
         $this->buffer .= $data;
         $this->emit('data');
     });
     $this->stream->on('close', function () {
         $this->close();
     });
     $this->on('data', function () {
         $this->onData();
     });
     $this->on('msg', function (Peer $peer, NetworkMessage $msg) {
         $this->emit($msg->getCommand(), [$peer, $msg->getPayload()]);
     });
     return $this;
 }
예제 #16
0
 /**
  *
  */
 public function on()
 {
     $client = stream_socket_client('tcp://' . $this->address . ':' . $this->port);
     $buffer = $this->buffer;
     $stock = $this->stock;
     $conn = new Stream($client, $this->loop);
     $conn->on('data', function ($data) use($conn, $buffer, $stock) {
         $buffer->setCache($data);
         if (strspn($buffer->getCache(), 'close')) {
             $conn->close();
             exit;
         }
         if (strpos($buffer->getCache(), PHP_EOL) !== false) {
             echo $data;
         }
         $stock->stockize($buffer->getCache());
     });
 }
예제 #17
0
 public static function postInstall()
 {
     Config::makeBinDirectory();
     $loop = Factory::create();
     $file = Config::getBinFile();
     $url = 'https://yt-dl.org/downloads/latest/youtube-dl';
     $readStream = fopen($url, 'r');
     $writeStream = fopen($file, 'w');
     stream_set_blocking($readStream, 0);
     stream_set_blocking($writeStream, 0);
     $read = new Stream($readStream, $loop);
     $write = new Stream($writeStream, $loop);
     $read->on('end', function () use($file) {
         chmod($file, 0777);
         echo "Finished downloading {$file}\n";
     });
     $read->pipe($write);
     $loop->run();
 }
예제 #18
0
 /**
  * Handle http request
  *
  * @param HttpRequestEvent $event
  */
 public function onRequest(HttpRequestEvent $event)
 {
     $filePath = $event->getRequest()->getPath();
     foreach ($this->application->getMetadata() as $name => $metadata) {
         /* @var $metadata \PhpCollection\Map */
         if ($metadata->containsKey('assets')) {
             $assumedFilePath = $metadata->get('application_path')->get() . DIRECTORY_SEPARATOR . $metadata->get('assets')->get() . DIRECTORY_SEPARATOR . $filePath;
             $assumedFilePath = realpath($assumedFilePath);
             if (file_exists($assumedFilePath) && is_file($assumedFilePath)) {
                 $event->stopPropagation();
                 $fileStream = new Stream(fopen($assumedFilePath, 'r'), $this->serverLoop);
                 $event->getResponse()->getHeaders()->set('Content-Type', MimeTypeGuesser::getMimeType($assumedFilePath));
                 $event->getResponse()->dispatchHeaders();
                 $fileStream->pipe($event->getResponse()->getReactResponse());
                 $fileStream->on('end', 'gc_collect_cycles');
                 gc_collect_cycles();
             }
         }
     }
 }
예제 #19
0
파일: Client.php 프로젝트: clue/socks-react
 /**
  * Internal helper used to handle the communication with the SOCKS server
  *
  * @param Stream      $stream
  * @param string      $host
  * @param int         $port
  * @return Promise Promise<stream, Exception>
  * @internal
  */
 public function handleConnectedSocks(Stream $stream, $host, $port)
 {
     $deferred = new Deferred(function ($_, $reject) {
         $reject(new RuntimeException('Connection attempt cancelled while establishing socks session'));
     });
     $reader = new StreamReader($stream);
     $stream->on('data', array($reader, 'write'));
     if ($this->protocolVersion === '5') {
         $promise = $this->handleSocks5($stream, $host, $port, $reader);
     } else {
         $promise = $this->handleSocks4($stream, $host, $port, $reader);
     }
     $promise->then(function () use($deferred, $stream) {
         $deferred->resolve($stream);
     }, function ($error) use($deferred) {
         $deferred->reject(new Exception('Unable to communicate...', 0, $error));
     });
     $deferred->promise()->then(function (Stream $stream) use($reader) {
         $stream->removeAllListeners('end');
         $stream->removeListener('data', array($reader, 'write'));
         return $stream;
     }, function ($error) use($stream) {
         $stream->close();
         return $error;
     });
     $stream->on('end', function (Stream $stream) use($deferred) {
         $deferred->reject(new Exception('Premature end while establishing socks session'));
     });
     return $deferred->promise();
 }
예제 #20
0
 public function __construct(LoopInterface $loop)
 {
     $bspcProcess = proc_open('bspc subscribe report', [['pipe', 'r'], ['pipe', 'w']], $pipes);
     $bspcStdout = new Stream($pipes[1], $loop);
     $bspcStdout->on('data', [$this, 'onUpdate']);
 }
예제 #21
0
파일: Server.php 프로젝트: mcocaro/trevor
 public function onConnection(Stream $conn)
 {
     printf("Connected: %s\n", $conn->getRemoteAddress());
     $conn->on('data', [$this, 'onData']);
     $conn->on('end', [$this, 'onEnd']);
 }
예제 #22
0
 /**
  * @covers React\Stream\Stream::handleData
  */
 public function testDataErrorShouldEmitErrorAndClose()
 {
     $stream = fopen('php://temp', 'r+');
     // add a filter which returns an error when encountering an 'a' when reading
     Filter\append($stream, function ($chunk) {
         if (strpos($chunk, 'a') !== false) {
             throw new \Exception('Invalid');
         }
         return $chunk;
     }, STREAM_FILTER_READ);
     $loop = $this->createLoopMock();
     $conn = new Stream($stream, $loop);
     $conn->on('data', $this->expectCallableNever());
     $conn->on('error', $this->expectCallableOnce());
     $conn->on('close', $this->expectCallableOnce());
     fwrite($stream, "foobar\n");
     rewind($stream);
     $conn->handleData($stream);
 }
예제 #23
0
 /**
  * @covers React\Stream\Stream::handleData
  */
 public function testClosingStreamInDataEventShouldNotTriggerError()
 {
     $stream = fopen('php://temp', 'r+');
     $loop = $this->createLoopMock();
     $conn = new Stream($stream, $loop);
     $conn->on(Event::DATA, function ($data, $stream) {
         $stream->close();
     });
     fwrite($stream, "foobar\n");
     rewind($stream);
     $conn->handleData($stream);
 }
예제 #24
0
 /**
  * @inheritDoc
  */
 public function onData(\Closure $closure)
 {
     $this->reactStream->on('data', $closure);
 }
예제 #25
0
 public function initAdapted(\GearmanJob $job)
 {
     $this->loop = Factory::create();
     $this->read = new \React\Stream\Stream(STDIN, $this->loop);
     $this->read->bufferSize = 8192;
     $this->write = new \React\Stream\Stream(STDOUT, $this->loop);
     $this->write->bufferSize = 8192;
     $this->job = $job;
     //protect from repeated execution
     $initStart = false;
     $pmErrorDtoAlreadySent = false;
     /**
      * Receive sockets params json from PM to set it into performer
      */
     $this->read->on('data', function ($data) use($initStart, $pmErrorDtoAlreadySent) {
         if (!is_array($this->pmWorkerDta)) {
             $this->pmWorkerDta = @json_decode($data, true);
             if ($this->pmWorkerDta !== false && is_array($this->pmWorkerDta)) {
                 if ($initStart === false) {
                     $initStart = true;
                     try {
                         $this->initBasicParams();
                         $this->adaptedService->getTerminatorPauseStander()->setPublisherPmSocketAddress($this->pmWorkerDta[DataTransferConstants::PUBLISHER_PM]);
                         $this->adaptedService->getTerminatorPauseStander()->setUSleepTime(5000000);
                         $performerSocketParams = new PerformerSocketsParamsDto();
                         $performerSocketParams->setRequestPulsarRsSocketAddress($this->pmWorkerDta[DataTransferConstants::REQUEST_PULSAR_RS]);
                         $performerSocketParams->setPublisherPulsarSocketAddress($this->pmWorkerDta[DataTransferConstants::PUBLISHER_PULSAR]);
                         $performerSocketParams->setPushPulsarSocketAddress($this->pmWorkerDta[DataTransferConstants::PUSH_PULSAR]);
                         $this->adaptedService->getZmqPerformer()->setSocketsParams($performerSocketParams);
                         $this->adaptedService->getZmqPerformer()->setLogger($this->logger);
                         $this->adaptedService->serviceExec();
                         $this->adaptedService->getExecutionDto()->setExecutionMessage($this->adaptedService->getParams());
                         $this->job->sendComplete(serialize($this->adaptedService->getExecutionDto()));
                         $this->jobInfoWasSent = true;
                         $this->logger->critical("Job complete was sent.");
                     } catch (\Exception $e) {
                         $errorMsg = "Adapter die in Exception with \$e: " . $e->getMessage() . "|params: " . serialize($this->adaptedService->getParams());
                         //. $e->getTraceAsString();
                         $this->logger->critical($errorMsg . " | " . serialize($this->pmWorkerDta));
                         $this->job->sendComplete(serialize(InspectionHelper::prepareErrorExecutionDto($this->adaptedService->getTaskId(), $errorMsg)));
                         $this->jobInfoWasSent = true;
                         $this->logger->critical("Job complete with exception was sent.");
                         die;
                     }
                     $this->loop->nextTick(function () {
                         $this->loop->stop();
                     });
                 }
             } else {
                 if ($pmErrorDtoAlreadySent === false) {
                     $pmErrorDtoAlreadySent = true;
                     $pmErrorArr = [];
                     $pmErrorArr[DataTransferConstants::ERROR_LEVEL] = ErrorsConstants::CRITICAL;
                     $pmErrorArr[DataTransferConstants::ERROR_REASON] = PmErrorConstants::WORKER_NOT_RECEIVE_CORRECT_DTO;
                     $pmErrorArr[DataTransferConstants::ERROR_ELEMENT] = $this->pmWorkerDta;
                     //write to PM's allotted STDIN about critical error
                     $this->write->write(json_encode($pmErrorArr));
                     $this->loop->nextTick(function () {
                         $this->loop->stop();
                     });
                 }
             }
         }
     });
     $timerIteration = 0;
     $this->loop->addPeriodicTimer(3, function (Timer $timer) use(&$timerIteration) {
         if ($this->pmWorkerDta === null) {
             if ($timerIteration > $this->maxTimerIteration) {
                 $this->initBasicParams();
                 die;
             }
             $timerIteration++;
         } else {
             $timer->cancel();
         }
     });
     $this->loop->run();
     if ($pmErrorDtoAlreadySent) {
         die;
     }
 }
예제 #26
0
 /**
  * Connection constructor.
  * @param Stream $stream
  * @param RequestFactory $requestFactory
  */
 public function __construct(Stream $stream, RequestFactory $requestFactory)
 {
     $this->factory = $requestFactory;
     $this->stream = $stream;
     $this->stream->on('data', [$this, 'onData']);
 }
 protected function saveTo()
 {
     $saveTo = $this->options['sink'];
     $writeStream = fopen($saveTo, 'w');
     stream_set_blocking($writeStream, 0);
     $saveToStream = new ReactStream($writeStream, $this->loop);
     $saveToStream->on('end', function () {
         $this->onEnd();
     });
     $this->httpResponse->pipe($saveToStream);
 }
예제 #28
0
 /**
  * @dataProvider loopProvider
  */
 public function testDoesNotWriteDataIfClientSideHasBeenClosed($condition, $loopFactory)
 {
     if (true !== $condition()) {
         return $this->markTestSkipped('Loop implementation not available');
     }
     $loop = $loopFactory();
     $server = stream_socket_server('tcp://localhost:0');
     $client = stream_socket_client(stream_socket_get_name($server, false));
     $peer = stream_socket_accept($server);
     $streamA = new Stream($peer, $loop);
     $streamB = new Stream($client, $loop);
     // end streamA without writing any data
     $streamA->pause();
     $streamA->write('hello');
     $streamA->on('close', $this->expectCallableOnce());
     $streamB->on('data', $this->expectCallableNever());
     $streamB->close();
     $loop->run();
     $streamA->close();
     $streamB->close();
 }
예제 #29
0
require __DIR__ . '/../vendor/autoload.php';
$loop = Factory::create();
if (function_exists('posix_isatty') && posix_isatty(STDIN)) {
    // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
    shell_exec('stty -icanon -echo');
}
// process control codes from STDIN
$stdin = new Stream(STDIN, $loop);
$parser = new ControlCodeParser($stdin);
$stdout = new Stream(STDOUT, $loop);
$stdout->pause();
// pass all c0 codes through to output
$parser->on('c0', array($stdout, 'write'));
// replace any color codes (SGR) with a random color
$parser->on('csi', function ($code) use($stdout) {
    // we read any color code (SGR) on the input
    // assign a new random foreground and background color instead
    if (substr($code, -1) === 'm') {
        $code = "[" . mt_rand(30, 37) . ';' . mt_rand(40, 47) . "m";
    }
    $stdout->write($code);
});
// reset to default color at the end
$stdin->on('close', function () use($stdout) {
    $stdout->write("");
});
// pass plain data to output
$parser->pipe($stdout, array('end' => false));
// start with random color
$stdin->emit('data', array(""));
$loop->run();
예제 #30
0
 /**
  * Processing one URL, opens pair of read-write streams and piping them
  *
  * @param AMQPClosure $closure A closure of message with another URL
  * @param EventLoop\LoopInterface $loop A loop, worker is run on
  *
  * @return bool Success flag
  *
  * @throws \Exception
  */
 private function processURL(AMQPClosure $closure, EventLoop\LoopInterface $loop)
 {
     $readStream = @fopen($closure->get(), 'r');
     if (!$readStream) {
         return $this->error($closure);
     }
     $tmpdir = \Bot::config('tmpdir');
     if (!file_exists($tmpdir)) {
         if (!mkdir($tmpdir, 0777, true)) {
             throw new \Exception('Cannot create downloading dirname ' . $tmpdir);
         }
     }
     $fWritePath = $tmpdir . "/" . md5($closure->get());
     $writeStream = fopen($fWritePath, 'w');
     if (!$writeStream) {
         throw new \Exception('Cannot open downloading file ' . $fWritePath);
     }
     $this->files[$fWritePath] = true;
     $read = new Stream($readStream, $loop);
     $write = new Stream($writeStream, $loop);
     $write->on('end', function () use($closure, $fWritePath) {
         unset($this->files[$fWritePath]);
         $this->success($closure);
     });
     $read->on('error', function () use($closure, $fWritePath) {
         unset($this->files[$fWritePath]);
         $this->error($closure);
     });
     $read->pipe($write);
 }