Пример #1
0
 protected function connectToAddress(string $address, float $timeout, bool $encrypt)
 {
     $url = \sprintf('%s://%s', $this->protocol, $address);
     $errno = null;
     $errstr = null;
     $context = \stream_context_create(\array_replace_recursive($this->options, ['socket' => ['connect' => $address]]));
     $socket = @\stream_socket_client($url, $errno, $errstr, $timeout ?: null, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT, $context);
     if (!\is_resource($socket)) {
         throw new SocketException(\sprintf('Could not connect to "%s" (%s): [%s] %s', $url, $this->peer, $errno, \trim($errstr)));
     }
     try {
         \stream_set_blocking($socket, false);
         \stream_set_read_buffer($socket, 0);
         \stream_set_write_buffer($socket, 0);
         if ($this->tcpNoDelay) {
             Socket::setTcpNoDelay($socket, true);
         }
         if ($encrypt) {
             yield from $this->encryptSocketClient($socket, $timeout);
         } else {
             (yield new AwaitWrite($socket, $timeout));
         }
         return $socket;
     } catch (\Throwable $e) {
         Socket::shutdown($socket);
         throw $e;
     }
 }
Пример #2
0
 public function __construct($stream)
 {
     parent::__construct($stream);
     stream_set_blocking($stream, 0);
     stream_set_write_buffer($stream, 0);
     $this->read = self::reader();
     $this->write = self::writer();
 }
Пример #3
0
 /**
  * Create a new pipe-based log handler.
  * 
  * @param string $pipe Output pipe, defaults to STDERR.
  */
 public function __construct($pipe = 'php://stderr', int $threshold = Logger::ALL, array $origins = [])
 {
     $pipe = \fopen($pipe, 'wb');
     \stream_set_blocking($pipe, false);
     \stream_set_write_buffer($pipe, 0);
     $this->writer = new SocketWriter($pipe);
     $this->threshold = $threshold;
     $this->origins = $origins;
 }
Пример #4
0
 public function _connect()
 {
     $this->_socket = @pfsockopen($this->_host, $this->_port, $errno, $errstr, $this->_timeout);
     if ($this->_socket === false) {
         return new PHPTCP_Error($errno, $errstr);
     }
     stream_set_write_buffer($this->_socket, 0);
     socket_set_timeout($this->_socket, $this->_timeout);
 }
 /**
  * Connect to Host
  *
  * @param  string         $host
  * @param  array          $ssl
  * @return AbstractClient
  */
 protected function connect($host, array $ssl)
 {
     $this->socket = stream_socket_client($host, $errno, $errstr, ini_get('default_socket_timeout'), STREAM_CLIENT_CONNECT, stream_context_create(array('ssl' => $ssl)));
     if (!$this->socket) {
         throw new Exception\RuntimeException(sprintf('Unable to connect: %s: %d (%s)', $host, $errno, $errstr));
     }
     stream_set_blocking($this->socket, 0);
     stream_set_write_buffer($this->socket, 0);
     return $this;
 }
Пример #6
0
 /**
  * @param resource $resource Stream resource.
  * @param bool $autoClose True to close the resource on destruct, false to leave it open.
  */
 public function __construct($resource, bool $autoClose = true)
 {
     parent::__construct($resource, $autoClose);
     stream_set_write_buffer($resource, 0);
     stream_set_chunk_size($resource, self::CHUNK_SIZE);
     $this->writeQueue = new \SplQueue();
     $this->onCancelled = function (Throwable $exception) {
         $this->free($exception);
     };
 }
Пример #7
0
 /**
  * add a new request to the pool.
  */
 public function add(Resource $r)
 {
     $stream = $r->stream;
     $id = (int) $stream;
     if (isset($this->streams[$id])) {
         return $this->streams[$id];
     }
     stream_set_blocking($stream, 0);
     stream_set_write_buffer($stream, 0);
     return $this->streams[$id] = $r;
 }
Пример #8
0
 protected function _connect()
 {
     $sURL = $this->asurls[$this->_environment];
     $streamContext = stream_context_create(array('ssl' => array('verify_peer' => isset($this->_rootCertificationAuthorityFile), 'cafile' => $this->_rootCertificationAuthorityFile, 'local_cert' => $this->_providerCertificateFile)));
     $this->_hSocket = @stream_socket_client($sURL, $nError, $sError, $this->_connectTimeout, STREAM_CLIENT_CONNECT, $streamContext);
     if (!$this->_hSocket) {
         throw new Exception("Unable to connect to '{$sURL}': {$sError} ({$nError})");
     }
     stream_set_blocking($this->_hSocket, 0);
     stream_set_write_buffer($this->_hSocket, 0);
     return true;
 }
Пример #9
0
 /**
  * @param resource $resource
  * @param LoopInterface $loop
  * @param bool $autoClose
  * @throws InvalidArgumentException
  */
 public function __construct($resource, LoopInterface $loop, $autoClose = true)
 {
     parent::__construct($resource, $autoClose);
     if (function_exists('stream_set_write_buffer')) {
         stream_set_write_buffer($this->resource, 0);
     }
     $this->loop = $loop;
     $this->listening = false;
     $this->paused = true;
     $this->buffer = new Buffer();
     $this->resume();
 }
Пример #10
0
 public function record($level, $logStr)
 {
     $timeStr = '[' . date('Y-m-d H:i:s O') . ']';
     $fp = fopen($this->_filename, 'ab');
     if (false !== $fp) {
         stream_set_write_buffer($fp, $this->_write_buff);
         fwrite($fp, $timeStr . ' ' . $logStr . PHP_EOL);
         fclose($fp);
     } else {
         return false;
     }
     return true;
 }
Пример #11
0
 /**
  * Connect to Kafka via socket
  * 
  * @return void
  */
 public function connect()
 {
     if (!is_resource($this->conn)) {
         $this->conn = stream_socket_client('tcp://' . $this->host . ':' . $this->port, $errno, $errstr);
         if (!$this->conn) {
             throw new RuntimeException($errstr, $errno);
         }
         stream_set_timeout($this->conn, $this->socketTimeout);
         stream_set_read_buffer($this->conn, $this->socketBufferSize);
         stream_set_write_buffer($this->conn, $this->socketBufferSize);
         //echo "\nConnected to ".$this->host.":".$this->port."\n";
     }
 }
Пример #12
0
 public function stream_set_option($option, $arg1, $arg2)
 {
     switch ($option) {
         case STREAM_OPTION_BLOCKING:
             stream_set_blocking($this->fileSource, $arg1);
             break;
         case STREAM_OPTION_READ_TIMEOUT:
             stream_set_timeout($this->fileSource, $arg1, $arg2);
             break;
         case STREAM_OPTION_WRITE_BUFFER:
             stream_set_write_buffer($this->fileSource, $arg1, $arg2);
     }
 }
Пример #13
0
 public function run()
 {
     if (!($ipcSocket = @stream_socket_client($this->ipcUri, $errno, $errstr, 5))) {
         throw new \RuntimeException(sprintf("Failed connecting to IPC server: (%d) %s", $errno, $errstr));
     }
     stream_set_write_buffer($ipcSocket, 0);
     stream_socket_shutdown($ipcSocket, STREAM_SHUT_RD);
     $openMsg = $this->getThreadId() . "\n";
     if (@fwrite($ipcSocket, $openMsg) !== strlen($openMsg)) {
         throw new \RuntimeException("Failed writing open message to IPC server");
     }
     $this->ipcSocket = $ipcSocket;
 }
Пример #14
0
 private function init()
 {
     $connection = @stream_socket_client('tcp://' . $this->host . ':' . $this->port);
     stream_set_write_buffer($connection, 0);
     stream_set_read_buffer($connection, 0);
     if (!$connection) {
         throw new \Exception('No SyncDaemon available.');
     }
     $data = trim(fgets($connection));
     if ($data != self::ACCEPT) {
         throw new \Exception('Connection faild. Wrong answer: ' . $data);
     }
     $this->connection = $connection;
 }
Пример #15
0
 /**
  * {@inheritdoc}
  */
 public function connect()
 {
     if ($this->sock) {
         return;
     }
     $this->sock = stream_socket_client($this->uri, $errno, $errstr, $this->timeout);
     if (!$this->sock) {
         throw new \RuntimeException("Can't connect to the server at '{$this->uri}' ({$errno}: {$errstr})");
     }
     stream_set_timeout($this->sock, $this->timeout);
     stream_set_blocking($this->sock, $this->blocking);
     stream_set_read_buffer($this->sock, 0);
     // 64k
     stream_set_write_buffer($this->sock, 0);
 }
Пример #16
0
 public function __construct($host, $port, $connection_timeout, $read_write_timeout = null, $context = null, $blocking = false)
 {
     $errstr = $errno = null;
     $this->sock = null;
     if ($context) {
         $remote = sprintf('tls://%s:%s', $host, $port);
         $this->sock = @stream_socket_client($remote, $errno, $errstr, $connection_timeout, STREAM_CLIENT_CONNECT, $context);
     } else {
         $remote = sprintf('tcp://%s:%s', $host, $port);
         $this->sock = @stream_socket_client($remote, $errno, $errstr, $connection_timeout, STREAM_CLIENT_CONNECT);
     }
     if (!$this->sock) {
         throw new RuntimeException("Error Connecting to server({$errno}): {$errstr} ");
     }
     if (null !== $read_write_timeout) {
         if (!stream_set_timeout($this->sock, $read_write_timeout)) {
             throw new \Exception("Timeout (stream_set_timeout) could not be set");
         }
     }
     /**
      * Manually set blocking & write buffer settings and make sure they are successfuly set
      * Use non-blocking as we dont want to stuck waiting for socket data while fread() w/o timeout
      */
     if (!stream_set_blocking($this->sock, $blocking)) {
         throw new \Exception("Blocking could not be set");
     }
     $rbuff = stream_set_read_buffer($this->sock, 0);
     if (!(0 === $rbuff)) {
         throw new \Exception("Read buffer could not be set");
     }
     /**
      * ! this is not reliably returns success (0)
      * ! but default buffer is pretty high (few Kb), so will not affect sending single small pushes
      *
      * Output using fwrite() is normally buffered at 8K.
      * This means that if there are two processes wanting to write to the same output stream (a file),
      * each is paused after 8K of data to allow the other to write.
      *
      * Ensures that all writes with fwrite() are completed
      * before other processes are allowed to write to that output stream
      */
     stream_set_write_buffer($this->sock, 0);
     /**
      * Set small chunk size (default=4096/8192)
      * Setting this to small values (100bytes) still does NOT help detecting feof()
      */
     stream_set_chunk_size($this->sock, 1024);
 }
Пример #17
0
 /**
  * Open a log file.
  *
  * @param string $date  The date for the log file.
  */
 private function openLog($date)
 {
     assert('is_string($date)');
     if ($this->file !== NULL && $this->file !== FALSE) {
         fclose($this->file);
         $this->file = NULL;
     }
     $fileName = $this->logDir . '/' . $date . '.log';
     $this->file = @fopen($fileName, 'a');
     if ($this->file === FALSE) {
         throw new SimpleSAML_Error_Exception('Error opening log file: ' . var_export($fileName, TRUE));
     }
     // Disable output buffering
     stream_set_write_buffer($this->file, 0);
     $this->fileDate = $date;
 }
Пример #18
0
 public static function connect(string $url, $workerId) : IpcClient
 {
     $errno = null;
     $errstr = null;
     $socket = @\stream_socket_client($url, $errno, $errstr, 5);
     if ($socket === false) {
         throw new \RuntimeException(\sprintf('Failed to connecto to IPC server "%s": [%s] %s', $url, $errno, $errstr));
     }
     \stream_set_read_buffer($socket, 0);
     \stream_set_write_buffer($socket, 0);
     $socket = new SocketStream($socket);
     $transmitter = new SocketTransmitter($socket);
     // Perform a blocking handshake.
     $transmitter->sendSync($workerId, SocketTransmitter::TYPE_HANDSHAKE);
     return new IpcClient($workerId, $socket, $transmitter);
 }
Пример #19
0
 function puts($file, $string, $mode = 'w')
 {
     $pointer = @fopen($file, $mode);
     if (!$pointer) {
         $pointer = fopen($file, 'w');
     }
     if ($pointer) {
         stream_set_write_buffer($pointer, 0);
         if (flock($pointer, LOCK_EX)) {
             rewind($pointer);
             fputs($pointer, $string);
             flock($pointer, LOCK_UN);
         }
         fclose($pointer);
     }
 }
Пример #20
0
 public function accept()
 {
     $client_socket = \stream_socket_accept($this->server_sock);
     $client_socket_id = (int) $client_socket;
     \stream_set_blocking($client_socket, 0);
     $this->client_sock[$client_socket_id] = $client_socket;
     $this->client_num++;
     if ($this->client_num > $this->max_connect) {
         $this->_closeSocket($client_socket);
         return false;
     } else {
         //设置写缓冲区
         \stream_set_write_buffer($client_socket, $this->write_buffer_size);
         return $client_socket_id;
     }
 }
 function open($sNombreArchivo)
 {
     // Intentar la apertura del archivo de bitácora
     if (is_null($this->LOGHANDLE)) {
         $hLogHandle = fopen($sNombreArchivo, 'at');
         if (!$hLogHandle) {
             if (function_exists('error_get_last')) {
                 $e = error_get_last();
             } else {
                 $e = array('message' => 'Failed to open file, error_get_last() not available.');
             }
             throw new Exception("AppLogger::open() - No se puede abrir archivo de log '{$sNombreArchivo}' - {$e['message']}");
         }
         stream_set_write_buffer($hLogHandle, 0);
         $this->LOGHANDLE = $hLogHandle;
     }
 }
Пример #22
0
 /**
  * Create a logger that is powered by the given executor.
  * 
  * The logger will create a secondary executor that will be triggered by the given executor using future ticks.
  * 
  * @param ExecutorInterface $executor
  * @param string $url Ouput URL, will be opened in append mode, defaults to STDERR.
  * @param string $threshold
  */
 public function __construct(ExecutorInterface $executor, string $url = 'php://stderr', string $threshold = '*')
 {
     $this->executor = $executor;
     $this->threshold = $this->getSeverity($threshold);
     $this->messages = new \SplQueue();
     $fp = @fopen($url, 'a+b');
     if ($fp === false) {
         throw new \RuntimeException(sprintf('Failed to open "%s": %s', $url, error_get_last()['message'] ?? ''));
     }
     stream_set_blocking($fp, false);
     stream_set_write_buffer($fp, 0);
     $this->stream = new SocketStream($fp);
     $this->events = new EventEmitter($this->executor);
     $this->events->observe(LogMessageEvent::class, function (LogMessageEvent $event) {
         yield from $this->logEvent($event);
     });
 }
Пример #23
0
 public function execute(...$args) : Command
 {
     $spec = [['pipe', 'r']];
     $command = $this->command;
     $options = [];
     $cwd = $this->dir ?? \getcwd();
     $env = \array_merge(\array_filter($_SERVER, 'is_scalar'), $this->env ?? []);
     if (\DIRECTORY_SEPARATOR === '\\') {
         $options['bypass_shell'] = true;
     }
     for ($i = 0; $i < 2; $i++) {
         $spec[] = ['pipe', $i ? 'a' : 'w'];
     }
     foreach ($this->options as $k => $v) {
         if (\strlen($k) === 1) {
             $command .= ' -' . $k;
         } else {
             $command .= ' --' . $k;
         }
         if ($v !== null) {
             $command .= ' ' . \escapeshellarg($v);
         }
     }
     foreach ($args as $arg) {
         if ($arg instanceof RawArg) {
             $command .= ' ' . $arg;
         } else {
             $command .= ' ' . \escapeshellarg($arg);
         }
     }
     $pipes = [];
     $process = @\proc_open($command, $spec, $pipes, $cwd, $env, $options);
     if ($process === false) {
         throw new \RuntimeException(\sprintf('Failed to execute command: "%s"', $command));
     }
     foreach ($pipes as &$pipe) {
         \stream_set_blocking($pipe, false);
         \stream_set_read_buffer($pipe, 0);
         \stream_set_write_buffer($pipe, 0);
     }
     $close = $this->stderr ? 1 : 2;
     @fclose($pipes[$close]);
     unset($pipes[$close]);
     return new Command($process, ...\array_values($pipes));
 }
Пример #24
0
 /**
  * connect to host
  * @param string $host
  * @param array $ssl
  * @return AbstractClient
  */
 protected function connect($host, array $ssl)
 {
     set_error_handler(function ($errno, $errstr, $errfile, $errline) {
         throw new \ErrorException($errstr, $errno, 1, $errfile, $errline);
     });
     try {
         $this->socket = stream_socket_client($host, $errno, $errstr, ini_get('default_socket_timeout'), STREAM_CLIENT_CONNECT, stream_context_create(['ssl' => $ssl]));
     } catch (\ErrorException $e) {
         throw new \RuntimeException(sprintf('Unable to connect: %s: %d (%s)', $host, $e->getCode(), $e->getMessage()));
     }
     restore_error_handler();
     if (!$this->socket) {
         throw new \RuntimeException(sprintf('Unable to connect: %s: %d (%s)', $host, $errno, $errstr));
     }
     stream_set_blocking($this->socket, 0);
     stream_set_write_buffer($this->socket, 0);
     return $this;
 }
Пример #25
0
 /**
  * Создание файла
  * @param string $content Содержимое файла
  * @param string $to Путь к создаваемому файлу
  * @param bool $append Добавлять в файл или пересоздавать его. По умолчанию пересоздаётся.
  * @return bool Признак, создан файл или нет
  */
 static function create($content, $to, $append = false)
 {
     $to = self::makeVirtualDir($to);
     // Если папки нет, то создаем её
     $dir = dirname($to);
     if (!is_dir($dir)) {
         mkdir($dir, 0775, true);
     }
     $result = false;
     // Создание файла
     if ($f = fopen($to, $append ? 'a' : 'w')) {
         stream_set_write_buffer($f, 20);
         fwrite($f, $content);
         fclose($f);
         $result = true;
     }
     self::deleteVirtualDir($to);
     return $result;
 }
Пример #26
0
 public function __construct(LevelProvider $level, $regionX, $regionZ)
 {
     $this->x = $regionX;
     $this->z = $regionZ;
     $this->levelProvider = $level;
     $this->filePath = $this->levelProvider->getPath() . "region/r.{$regionX}.{$regionZ}.mca";
     $exists = file_exists($this->filePath);
     touch($this->filePath);
     $this->filePointer = fopen($this->filePath, "r+b");
     stream_set_read_buffer($this->filePointer, 1024 * 16);
     //16KB
     stream_set_write_buffer($this->filePointer, 1024 * 16);
     //16KB
     if (!$exists) {
         $this->createBlank();
     } else {
         $this->loadLocationTable();
     }
 }
Пример #27
0
 function accept()
 {
     $client_socket = stream_socket_accept($this->server_sock, 0);
     //惊群
     if ($client_socket === false) {
         return false;
     }
     $client_socket_id = (int) $client_socket;
     stream_set_blocking($client_socket, $this->client_block);
     $this->client_sock[$client_socket_id] = $client_socket;
     $this->client_num++;
     if ($this->client_num > $this->max_connect) {
         sw_socket_close($client_socket);
         return false;
     } else {
         //设置写缓冲区
         stream_set_write_buffer($client_socket, $this->write_buffer_size);
         return $client_socket_id;
     }
 }
Пример #28
0
 /**
  * Threader::Threader()
  *
  * The constructor which opens the process.
  *
  * @param mixed $cmd - Execute a shell command
  * @param mixed $vars - Pass arguments to shell command
  * @param string $name - Identifies your thread (useful for debug)
  * @return void
  */
 function Threader($cmd = null, $vars = null, $name = null, $stdout_file = null)
 {
     $descriptorspec = array(self::STDIN => array("pipe", "r"), self::STDOUT => array("pipe", "w"), self::STDERR => array("pipe", "w"));
     if ($stdout_file) {
         $this->_stdout_file = $stdout_file;
         $descriptorspec[self::STDOUT] = array("file", $stdout_file, "w");
         core::dprint('[THREAD] LOG ' . $stdout_file);
     }
     $pipes = array();
     if (!empty($cmd)) {
         $this->threadName = $name;
         try {
             //    if ($err = stream_get_contents($pipes[2]))
             $command = "{$cmd} {$vars}";
             $this->rid = proc_open($command, $descriptorspec, $this->pipes, null, null);
             @stream_set_blocking($this->pipes[self::STDIN], 0);
             @stream_set_blocking($this->pipes[self::STDOUT], 0);
             @stream_set_blocking($this->pipes[self::STDERR], 0);
             @stream_set_write_buffer($this->pipes[self::STDIN], 0);
             @stream_set_write_buffer($this->pipes[self::STDOUT], 0);
             @stream_set_write_buffer($this->pipes[self::STDERR], 0);
             /*                
                          stream_set_blocking($this->pipes[self::STDIN]  , 0);
                          stream_set_blocking($this->pipes[self::STDOUT] , 0);
                          stream_set_blocking($this->pipes[self::STDERR] , 0);
                          
                          // don't buffer stdout or stderr
                          stream_set_write_buffer($this->pipes[self::STDIN], 0);
                          stream_set_write_buffer($this->pipes[self::STDOUT], 0);
                          stream_set_write_buffer($this->pipes[self::STDERR], 0);
             */
             // Display the current STDOUT meta data.
             // print_r(stream_get_meta_data($this->pipes[self::STDIN]));
             core::dprint("[THREAD] " . $command);
             $this->active = true;
         } catch (exception $e) {
             $this->active = false;
             $this->error = $e->getMessage();
         }
     }
 }
Пример #29
0
 /**
  * @param string $host
  * @param int $port
  * @param int $timeout
  * @throws TransportException
  */
 private function connect($host, $port, $timeout)
 {
     $this->socket = @fsockopen($host, $port, $errno, $errstr, $timeout);
     if (!$this->socket) {
         throw new TransportException('Cannot open socket', TransportException::NOT_INITIALIZED);
     }
     stream_set_read_buffer($this->socket, 0);
     stream_set_write_buffer($this->socket, 0);
     // handshake
     $header = $this->read(15);
     if ($header === false) {
         $this->onIoFailure(sprintf('during handshake (%s)', socket_strerror(socket_last_error($this->socket))));
     }
     extract(unpack('Vsize/a*protocol', $header));
     /** @var $size int */
     /** @var $protocol string */
     if ($size != 11 || $protocol != 'GBXRemote 2') {
         throw new TransportException('Wrong protocol header', TransportException::WRONG_PROTOCOL);
     }
     $this->lastNetworkActivity = time();
 }
Пример #30
0
 /**
  * 发送推送
  *
  * @param array $deviceArr 推送token
  * @param int $pushId      文案id
  * @param int $ruleId      推送类型
  * @param string $alert    推送信息
  * @param bool $pro        是否是测试
  * @param string $apnsCert 推送证书
  */
 public function pushApns($deviceArr, $pushId, $ruleId, $alert = '', $pro = TRUE, $apnsCert)
 {
     $notification = array();
     $this->_pempath = self::setPemPath();
     if (strlen($alert) > 0) {
         $notification['alert'] = $alert;
     }
     if (strlen($pushId) > 0) {
         $notification['pushid'] = $pushId;
     }
     if (strlen($ruleId) > 0) {
         $notification['rulid'] = $ruleId;
     }
     $notification['sound'] = $this->_sound;
     $notification['badge'] = $this->_badge;
     $body['aps'] = $notification;
     $APPLE_SERVER = $pro ? $this->_proUrl : $this->_testUrl;
     $streamContext = stream_context_create(array('ssl' => array('local_cert' => $this->_pempath . $apnsCert)));
     $apns = @stream_socket_client($APPLE_SERVER, $nError, $sError, 2, STREAM_CLIENT_CONNECT, $streamContext);
     stream_set_blocking($apns, 0);
     stream_set_write_buffer($apns, 0);
     if (!$apns) {
         print "Failed to connect {$nError} {$sError}\n";
         return;
     }
     foreach ($deviceArr as $v) {
         $device = mysql_escape_string($v['device']);
         $payload = json_encode($body);
         echo $payload;
         // format the message
         $msg = chr(0) . chr(0) . chr(32) . pack('H*', $device) . chr(0) . chr(strlen($payload)) . $payload;
         echo $msg;
         fwrite($apns, $msg);
     }
     @socket_close($apns);
     fclose($apns);
     var_dump($apns);
 }