private function connect() { // If we're in the process of connecting already return that same promise if ($this->connectPromisor) { return $this->connectPromisor->promise(); } // If a read watcher exists we know we're already connected if ($this->readWatcher) { return new Success($this); } $this->state = self::STATE_CONNECTING; $this->connectPromisor = new Deferred(); $socketPromise = connect($this->uri, ["timeout" => $this->timeout]); $onWrite = function ($watcherId) { if ($this->outputBufferLength === 0) { disable($watcherId); return; } $bytes = @fwrite($this->socket, $this->outputBuffer); if ($bytes === 0) { $this->state = self::STATE_DISCONNECTED; $this->onError(new ConnectException("Connection went away (write)", $code = 1)); } else { $this->outputBuffer = (string) substr($this->outputBuffer, $bytes); $this->outputBufferLength -= $bytes; } }; $socketPromise->when(function ($error, $socket) use($onWrite) { $connectPromisor = $this->connectPromisor; $this->connectPromisor = null; if ($error) { $this->state = self::STATE_DISCONNECTED; $connectPromisor->fail(new ConnectException("Connection attempt failed", $code = 0, $error)); return; } $this->state = self::STATE_CONNECTED; $this->socket = $socket; foreach ($this->handlers["connect"] as $handler) { $pipelinedCommand = $handler(); if (!empty($pipelinedCommand)) { $this->outputBuffer = $pipelinedCommand . $this->outputBuffer; $this->outputBufferLength += strlen($pipelinedCommand); } } $this->readWatcher = onReadable($this->socket, function () { $read = fread($this->socket, 8192); if ($read != "") { $this->parser->append($read); } elseif (!is_resource($this->socket) || @feof($this->socket)) { $this->state = self::STATE_DISCONNECTED; $this->onError(new ConnectException("Connection went away (read)", $code = 2)); } }); $this->writeWatcher = onWritable($this->socket, $onWrite, ["enable" => !empty($this->outputBuffer)]); $connectPromisor->succeed(); }); return $this->connectPromisor->promise(); }
/** * @return Promise */ private function connect() { if ($this->promisor) { return $this->promisor->promise(); } // Already connected if (is_resource($this->socket)) { return new Success(); } $this->promisor = new \Amp\Deferred(); /** @var $socketPromise Promise */ $socketPromise = \Amp\Socket\connect($this->uri, ['timeout' => 1000]); $socketPromise->when(function ($error, $socket) { $promisor = $this->promisor; $this->promisor = null; $this->socket = $socket; $this->reader = \Amp\onReadable($this->socket, [$this, "onRead"]); $this->writer = \Amp\onWritable($this->socket, [$this, "onWrite"]); $promisor->succeed(); }); return $this->promisor->promise(); }