@param int $timeout
@param int $attempts

@return Connection
977906
protected function connect($timeout = 5, $attempts = 10)
    {
        $url      = $this->endpoints[$this->method];
        $urlParts = parse_url($url);
        $scheme   = $urlParts['scheme'] == 'https' ? 'ssl://' : 'tcp://';
        $port     = $urlParts['scheme'] == 'https' ? 443 : 80;

        $requestParams = [];

        if ($this->lang) {
            $requestParams['language'] = $this->lang;
        }

        if (($this->method === self::METHOD_FILTER || $this->method === self::METHOD_USER) && count($this->trackWords) > 0) {
            $requestParams['track'] = implode(',', $this->trackWords);
        }
        if (($this->method === self::METHOD_FILTER || $this->method === self::METHOD_SITE) && count($this->followIds) > 0) {
            $requestParams['follow'] = implode(',', $this->followIds);
        }

        if ($this->method === self::METHOD_FILTER && $this->location) {
            $requestParams['locations'] = implode(',', $this->location->getBoundingBox());
        }

        if ($this->count <> 0) {
            $requestParams['count'] = $this->count;
        }

        $this->connection->open($scheme . $urlParts['host'], $port, $timeout, $attempts);
        $this->connection->authenticate($url, $requestParams, $this->oauth->getAuthorizationHeader($url, $requestParams));

        return $this->connection;
    }
504471
private function tryToRestore(int $attempt)
    {
        if (!$attempt) {
            return false;
        }
        $this->opened_socket = NULL;
        if (!$this->prepareSocket()) {
            return false;
        }

        $len_restored = $restored_block = 0;
        while ($len_restored < $this->fetched_length) {
            $restored_block = fread($this->opened_socket, $this->block_size);
            if ($restored_block === false) {
                return $this->tryToRestore($attempt - 1);
            }
            $len_restored += strlen($restored_block);
        }

        if ($len_restored > $this->fetched_length) {
            $last_block_len = $this->block_size - ($len_restored - $this->fetched_length);
            $block = substr($restored_block, $last_block_len);
        } else {
            $block = fread($this->opened_socket, $this->block_size);
            if ($block === false) {
                return $this->tryToRestore($attempt - 1);
            }
        }

        return $block;
    }
151221
public function receive($timeout = null)
    {
        if (null == $this->message) {
            try {
                if ($message = $this->doReceive($this->receiveCallback, $this, $timeout)) {
                    $this->message = $message;
                }
            } finally {
                call_user_func($this->finallyCallback, $this);
            }
        }

        return $this->message;
    }
464440
public function connect($host, $ssl = false, $port = 21, $timeout = 90)
    {
        if ($ssl) {
            $this->connection = @ftp_ssl_connect($host, $port, $timeout);
        } else {
            $this->connection = @ftp_connect($host, $port, $timeout);
        }

        if ($this->connection == null) {
            throw new Exception('Unable to connect');            
        } else {
            return $this;
        }
    }
475385
protected function _connect(
        $host, $port, $timeout, $secure, $context, $retries = 0
    )
    {
        $conn = '';
        if (!strpos($host, '://')) {
            switch (strval($secure)) {
            case 'ssl':
            case 'sslv2':
            case 'sslv3':
                $conn = $secure . '://';
                $this->_secure = true;
                break;

            case 'tlsv1':
                $conn = 'tls://';
                $this->_secure = true;
                break;

            case 'tls':
            default:
                $conn = 'tcp://';
                break;
            }
        }
        $conn .= $host;
        if ($port) {
            $conn .= ':' . $port;
        }

        $this->_stream = @stream_socket_client(
            $conn,
            $error_number,
            $error_string,
            $timeout,
            STREAM_CLIENT_CONNECT,
            stream_context_create($context)
        );

        if ($this->_stream === false) {
            /* From stream_socket_client() page: a function return of false,
             * with an error code of 0, indicates a "problem initializing the
             * socket". These kind of issues are seen on the same server
             * (and even the same user account) as sucessful connections, so
             * these are likely transient issues. Retry up to 3 times in these
             * instances. */
            if (!$error_number && ($retries < 3)) {
                return $this->_connect($host, $port, $timeout, $secure, ++$retries, $context);
            }

            $e = new Client\Exception(
                'Error connecting to server.'
            );
            $e->details = sprintf("[%u] %s", $error_number, $error_string);
            throw $e;
        }

        stream_set_timeout($this->_stream, $timeout);

        if (function_exists('stream_set_read_buffer')) {
            stream_set_read_buffer($this->_stream, 0);
        }
        stream_set_write_buffer($this->_stream, 0);

        $this->_connected = true;
    }
982060
public final Connection connectNow(Duration timeout) {
		Objects.requireNonNull(timeout, "timeout");
		try {
			return Objects.requireNonNull(connect().block(timeout), "aborted");
		}
		catch (IllegalStateException e) {
			if (e.getMessage().contains("blocking read")) {
				throw new IllegalStateException("TcpClient couldn't be started within "
						+ timeout.toMillis() + "ms");
			}
			throw e;
		}
	}
1180852
private function establishConnection($host, $port, $timeout)
    {
        $deferred = new Deferred();

        $timer = $this->loop->addTimer(
            $timeout,
            function () use ($deferred, $timeout) {
                $exception = new \RuntimeException(sprintf('Connection timed out after %d seconds.', $timeout));
                $deferred->reject($exception);
            }
        );

        $this->connector->connect($host.':'.$port)
            ->always(function () use ($timer) {
                $this->loop->cancelTimer($timer);
            })
            ->then(function (DuplexStreamInterface $stream) use ($deferred) {
                $stream->on('data', function ($data) {
                    $this->handleReceive($data);
                });

                $stream->on('close', function () {
                    $this->handleClose();
                });

                $stream->on('error', function (\Exception $e) {
                    $this->handleError($e);
                });

                $deferred->resolve($stream);
            })
            ->otherwise(function (\Exception $e) use ($deferred) {
                $deferred->reject($e);
            });

        return $deferred->promise();
    }
889591
private function establishConnection($host, $port, Connection $connection, $timeout)
    {
        $this->logger->info(sprintf('Connecting to %s:%d...', $host, $port));

        return $this->client->connect($host, $port, $connection, $timeout);
    }
1343306
public function get_session_lock($rowid, $timeout) {
        parent::get_session_lock($rowid, $timeout);

        $fullname = $this->dbname.'-'.$this->prefix.'-session-'.$rowid;
        $sql = 'SELECT MOODLELIB.GET_LOCK(:lockname, :locktimeout) FROM DUAL';
        $params = array('lockname' => $fullname , 'locktimeout' => $timeout);
        $this->query_start($sql, $params, SQL_QUERY_AUX);
        $stmt = $this->parse_query($sql);
        $this->bind_params($stmt, $params);
        $result = oci_execute($stmt, $this->commit_status);
        if ($result === false) { // Any failure in get_lock() raises error, causing return of bool false
            throw new dml_sessionwait_exception();
        }
        $this->query_end($result, $stmt);
        oci_free_statement($stmt);
    }
116417
function attempt() {
      connections[id].attempts++;
      if (connections[id].attempts > retry) {
        connections[id].attempts = 0;
        connections[id].deny++;
        self.log(chalk.yellow("Access denied: too many attempts."));
        callback("Access denied: too many attempts.", false);
        return;
      }
      if (connections[id].deny >= deny && unlockTime > 0) {
        setTimeout(function(){
          connections[id].deny = 0;
        }, unlockTime);
        connections[id].attempts = 0;
        self.log(chalk.yellow("Account locked out: too many login attempts."));
        callback("Account locked out: too many login attempts.", false);
        return;
      }
      gather(function(user, pass){
        user = search(user, pass, users);
        if (user) {
          connections[id].attempts = 0;
          connections[id].deny = 0;
          callback("Successfully Authenticated.", true);
        } else {
          state.pass = void 0;
          setTimeout(function(){
            if (connections[id].attempts <= retry) {
              self.log("Access denied.");
            }
            attempt();
          }, retryTime);
        }
      });
    }
1067573
public function connect($timeout = null)
    {
        if ($timeout === null) {
            $timeout = intval(ini_get('default_socket_timeout'));
        }

        $this->timeout      = $timeout;
        $this->streamSocket = $this->getStream(
            $this->options->getAddress(), $timeout, $this->options->getStreamContext());
        $this->setStreamTimeout($timeout);

        $infoResponse = $this->receive();

        if ($this->isErrorResponse($infoResponse) === true) {
            throw Exception::forFailedConnection($infoResponse);
        } else {
            $this->processServerInfo($infoResponse);
            if ($this->serverInfo->isTLSRequired()) {
                set_error_handler(
                    function ($errno, $errstr, $errfile, $errline) {
                        restore_error_handler();
                        throw Exception::forFailedConnection($errstr);
                    });

                if (!stream_socket_enable_crypto(
                        $this->streamSocket, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT)) {
                    throw Exception::forFailedConnection('Error negotiating crypto');
                }

                restore_error_handler();
            }
        }

        $msg = 'CONNECT '.$this->options;
        $this->send($msg);
        $this->ping();
        $pingResponse = $this->receive();

        if ($this->isErrorResponse($pingResponse) === true) {
            throw Exception::forFailedPing($pingResponse);
        }
    }
1371105
function set_timeout($timeout) {
        if (!is_integer($timeout)) {
            if (is_numeric($timeout)) {
                $this->timeout = (integer)$timeout;
                return true;
            }
            return false;
        }
        $this->timeout = $timeout;
        return true;
    }
233779
public function block($timeout, $callback = null)
    {
        $starting = time();

        $id = Str::random(20);

        while (! $slot = $this->acquire($id)) {
            if (time() - $timeout >= $starting) {
                throw new LimiterTimeoutException;
            }

            usleep(250 * 1000);
        }

        if (is_callable($callback)) {
            try {
                return tap($callback(), function () use ($slot, $id) {
                    $this->release($slot, $id);
                });
            } catch (Exception $exception) {
                $this->release($slot, $id);

                throw $exception;
            }
        }

        return true;
    }
821544
public function setTimeout($timeout)
    {
        $this->params['timeout'] = (int) $timeout;
        $this->buffer->setParam('timeout', (int) $timeout);

        return $this;
    }
224357
public function setRequestTimeout($timeout)
    {
        if (!is_int($timeout) || $timeout < 0) {
            throw new Exception("Invalid value supplied for request timeout: $timeout");
        }

        $this->requestTimeout = $timeout;
        return $this;
    }
98044
public function get_session_lock($rowid, $timeout) {
        // NOTE: there is a potential locking problem for database running
        //       multiple instances of moodle, we could try to use pg_advisory_lock(int, int),
        //       luckily there is not a big chance that they would collide
        if (!$this->session_lock_supported()) {
            return;
        }

        parent::get_session_lock($rowid, $timeout);

        $timeoutmilli = $timeout * 1000;

        $sql = "SET statement_timeout TO $timeoutmilli";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = pg_query($this->pgsql, $sql);
        $this->query_end($result);

        if ($result) {
            pg_free_result($result);
        }

        $sql = "SELECT pg_advisory_lock($rowid)";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $start = time();
        $result = pg_query($this->pgsql, $sql);
        $end = time();
        try {
            $this->query_end($result);
        } catch (dml_exception $ex) {
            if ($end - $start >= $timeout) {
                throw new dml_sessionwait_exception();
            } else {
                throw $ex;
            }
        }

        if ($result) {
            pg_free_result($result);
        }

        $sql = "SET statement_timeout TO DEFAULT";
        $this->query_start($sql, null, SQL_QUERY_AUX);
        $result = pg_query($this->pgsql, $sql);
        $this->query_end($result);

        if ($result) {
            pg_free_result($result);
        }
    }
150072
public function retry(int $times = 1, int $timeout = 0): Call
    {
        \assert('$times >= 1 && $timeout >= 0');
        \assert('$this->current !== null');
        if ($this->current !== null) {
            $this->catchers[$this->current][] = function (...$args) use ($times, $timeout) {
                static $lTimes;
                if ($lTimes === null) {
                    $lTimes = $times;
                }
                // the first end() is already invoked
                $lTimes--;
                if ($lTimes > 0) {
                    usleep($timeout);
                    return $this->end(...$args);
                }
                return null;
            };
        }
        return $this;
    }