Returns an stream socket to the desired server.

@param string $address Server url string.
@param float  $timeout Number of seconds until the connect() system call should timeout.

@throws \Exception Exception raised if connection fails.
@return resource
760508
private function getStream($address, $timeout, $context)
    {
        $errno  = null;
        $errstr = null;

        set_error_handler(
            function () {
                return true;
            }
        );

        $fp = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
        restore_error_handler();

        if ($fp === false) {
            throw Exception::forStreamSocketClientError($errstr, $errno);
        }

        $timeout      = number_format($timeout, 3);
        $seconds      = floor($timeout);
        $microseconds = (($timeout - $seconds) * 1000);
        stream_set_timeout($fp, $seconds, $microseconds);

        return $fp;
    }
172404
private SocketChannel connectToHost(SocketAddress hostAddr)
            throws IOException
    {
        SocketChannel socket = null;
        while (socket == null) {
            try {
                socket = SocketChannel.open(hostAddr);
            }
            catch (java.net.ConnectException e) {
                LOG.warn("Joining host failed: " + e.getMessage() + " retrying..");
                try {
                    Thread.sleep(250); //  milliseconds
                }
                catch (InterruptedException dontcare) {}
            }
        }
        return socket;
    }
1017221
public function openSocket(int $timeout = 5, callable $openWith = null): Stream
    {
        $socket = $this->createSocket();
        if (null !== $openWith) {
            $socket->openWith($openWith);
        }

        return $socket->connect()->setTimeout($timeout);
    }
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);
        }
    }
688151
public function dataAvailable($timeout = 0)
    {
        $readFds = [$this->_input];
        $writeFds = null;
        $errorFds = null;
        $readyFds = stream_select($readFds, $writeFds, $errorFds, $timeout);

        return ($readyFds > 0);
    }
231199
protected function connect()
    {
        $host = "{$this->socketProtocol}://{$this->hostname}";
        if ($this->socketPort) {
            $host .= ":{$this->socketPort}";
        }
        $socketStream = @stream_socket_client($host, $errorNumber, $errorMessage, $this->socketOptions['connectionTimeout']);
        if (!is_resource($socketStream)) {
            throw new \Exception("{$errorNumber}: Error connecting to socket: [{$errorMessage}]");
        }
        stream_set_timeout($socketStream, $this->socketOptions['streamTimeout']);
        stream_set_blocking($socketStream, true);
        $this->socketResource = $socketStream;
        return $this;
    }
1076777
public function connect($address, $port = 0)
    {
        try {
            socket_connect($this->socket, $address, $port);
        } catch (\Exception $e) {
            throw new CreateSocketException($e->getMessage());
        }
    }
615157
public function connect($host, $port, Connection $connection, $timeout = 5)
    {
        $deferred = new Deferred();
        $this->disconnect()
            ->then(function () use ($deferred, $host, $port, $connection, $timeout) {
                $this->establishConnection($host, $port, $connection, $timeout)
                    ->then(function () use ($deferred) {
                        $deferred->resolve($this);
                    })
                    ->otherwise(function (\Exception $error) use ($deferred) {
                        $deferred->reject($error);
                    });
            })
            ->otherwise(function () use ($deferred) {
                $deferred->reject($this);
            });

        return $deferred->promise();
    }
1140209
public static function http_get($url, $timeOut = 5, $connectTimeOut = 5) {
		$oCurl = curl_init ();
		if (stripos ( $url, "http://" ) !== FALSE || stripos ( $url, "https://" ) !== FALSE) {
			curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE );
			curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, FALSE );
		}
		curl_setopt($oCurl, CURLOPT_URL, $url );
		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($oCurl, CURLOPT_TIMEOUT, $timeOut);
        curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, $connectTimeOut);
		$sContent = curl_exec ( $oCurl );
		$aStatus = curl_getinfo ( $oCurl );
        $error = curl_error( $oCurl );
		curl_close ( $oCurl );
		if (intval ( $aStatus ["http_code"] ) == 200) {
			return array(
					'status' => true,
					'content' => $sContent,
					'code' => $aStatus ["http_code"],
			);
		} else {
			return array(
					'status' => false,
					'content' => json_encode(array("error" => $error, "url" => $url)),
					'code' => $aStatus ["http_code"],
			);
		}
	}
776283
public function send(string $address, string $data): Promise
    {
        \assert($this->isAddressValid($address), "Invalid packet address");

        if (!$this->socket) {
            return new Failure(new SocketException('The endpoint is not writable'));
        }

        $result = @\stream_socket_sendto($this->socket, $data, 0, $address);

        if ($result < 0 || $result === false) {
            $error = \error_get_last();
            return new Failure(new SocketException('Could not send packet on endpoint: ' . $error['message']));
        }

        return new Success($result);
    }
629536
protected function _receive($timeout = null)
    {
        $this->checkConnection();

        if ($timeout !== null) {
            stream_set_timeout($this->_connection, $timeout);
        }

        $response = fgets($this->_connection, 1024);
        $info = stream_get_meta_data($this->_connection);

        if (!empty($info['timed_out'])) {
            throw new SMTPException(__('%s has timed out', array($this->_host)));
        } elseif ($response === false) {
            throw new SMTPException(__('Could not read from %s', array($this->_host)));
        }

        return $response;
    }
703748
public function getResponses(array $sockets, $timeout, $stream_timeout)
    {

        // Set the loop to active
        $loop_active = true;

        // Will hold the responses read from the sockets
        $responses = [];

        // To store the sockets
        $sockets_tmp = [];

        // Loop and pull out all the actual sockets we need to listen on
        foreach ($sockets as $socket_id => $socket_data) {
            // Get the socket
            /* @var $socket \GameQ\Query\Core */
            $socket = $socket_data['socket'];

            // Append the actual socket we are listening to
            $sockets_tmp[$socket_id] = $socket->get();

            unset($socket);
        }

        // Init some variables
        $read = $sockets_tmp;
        $write = null;
        $except = null;

        // Check to see if $read is empty, if so stream_select() will throw a warning
        if (empty($read)) {
            return $responses;
        }

        // This is when it should stop
        $time_stop = microtime(true) + $timeout;

        // Let's loop until we break something.
        while ($loop_active && microtime(true) < $time_stop) {
            // Check to make sure $read is not empty, if so we are done
            if (empty($read)) {
                break;
            }

            // Now lets listen for some streams, but do not cross the streams!
            $streams = stream_select($read, $write, $except, 0, $stream_timeout);

            // We had error or no streams left, kill the loop
            if ($streams === false || ($streams <= 0)) {
                break;
            }

            // Loop the sockets that received data back
            foreach ($read as $socket) {
                /* @var $socket resource */

                // See if we have a response
                if (($response = fread($socket, 8192)) === false) {
                    continue; // No response yet so lets continue.
                }

                // Check to see if the response is empty, if so we are done with this server
                if (strlen($response) == 0) {
                    // Remove this server from any future read loops
                    unset($sockets_tmp[(int)$socket]);
                    continue;
                }

                // Add the response we got back
                $responses[(int)$socket][] = $response;
            }

            // Because stream_select modifies read we need to reset it each time to the original array of sockets
            $read = $sockets_tmp;
        }

        // Free up some memory
        unset($streams, $read, $write, $except, $sockets_tmp, $time_stop, $response);

        // Return all of the responses, may be empty if something went wrong
        return $responses;
    }
1327635
public function wait($timeout = 60)
    {
        $timeoutMicro = $timeout !== null ? microtime(true) + (float)$timeout : null;
        while ($this->isRunning()) {
            if ($timeout !== null && microtime(true) >= $timeoutMicro) {
                return null;
            }
            usleep(1000);
        }

        return $this->getExitCode();
    }
238430
public function getQueue($name, $timeout = null)
    {
        if (!is_string($name)) {
            throw new Exception('$name is not a string');
        }

        if ((null !== $timeout) && !is_integer($timeout)) {
            throw new Exception('$timeout must be an integer');
        }

        if(!$this->getQueueId($name)) {
            $this->create($name, $timeout);
        }

        $q = new Queue($name, $timeout);
        $q->setManager($this);
        return $q;
    }
447505
public static function sendData($address, $buffer)
    {
        $socket = stream_socket_client($address);
        if(!$socket)
        {
            return false;
        }
        return stream_socket_sendto($socket, $buffer) == strlen($buffer);
    }
942399
public function write($buffer)
    {
        $ret = @socket_write($this->resource, $buffer);
        if ($ret === false) {
            throw Exception::createFromSocketResource($this->resource);
        }
        return $ret;
    }
296197
private function streamSelect(array &$read, array &$write, $timeout)
    {
        if ($read || $write)
        {
            $except = null;

            return @stream_select($read, $write, $except, $timeout === null ? null : 0, $timeout);
        }

        usleep($timeout);

        return 0;
    }