@param string $host
@param int    $port
@param int    $sendTimeout
@param int    $receiveTimeout

@return TSocket
@author Mario Mueller
167127
private static function createSocket($host, $port, $sendTimeout, $receiveTimeout)
    {
        $socket = new TSocket($host, $port, true);
        if (null !== $sendTimeout) {
            $socket->setSendTimeout($sendTimeout);
        }

        if (null !== $receiveTimeout) {
            $socket->setRecvTimeout($receiveTimeout);
        }

        return $socket;
    }
33272
public static function create($host, $port, $password)
    {
        $factory = new \Socket\Raw\Factory();
        $socket = $factory->createClient(sprintf('%s:%s', $host, $port));

        return new \gries\Rcon\Connection($socket, $password);
    }
723714
protected function checkConnection($host, $port)
    {
        $host = ($port == 443) ? 'ssl://' . $host : 'tcp://' . $host;

        // If the connection could not be established, fsockopen sadly does not
        // only return false (as documented), but also always issues a warning.
        if (($this->connection === null) &&
            (($this->connection = @stream_socket_client($host . ':' . $port, $errno, $errstr)) === false)) {
            // This is a bit hackisch...
            $this->connection = null;
            throw new \RuntimeException('fail');
        }
    }
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;
    }
1330114
function connect($host, $port, $timeout = 0.1, $nonblock = false)
    {
        //判断超时为0或负数
        if (empty($host) or empty($port) or $timeout <= 0)
        {
            $this->errCode = -10001;
            $this->errMsg = "param error";
            return false;
        }
        $this->host = $host;
        $this->port = $port;
        //创建socket
        $this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($this->sock === false)
        {
            $this->set_error();
            return false;
        }
        //设置connect超时
        $this->set_timeout($timeout, $timeout);
        $this->setopt(SO_REUSEADDR, 1);
        //非阻塞模式下connect将立即返回
        if ($nonblock)
        {
            socket_set_nonblock($this->sock);
            @socket_connect($this->sock, $this->host, $this->port);
            return true;
        }
        else
        {
            //这里的错误信息没有任何意义，所以屏蔽掉
            if (@socket_connect($this->sock, $this->host, $this->port))
            {
                $this->connected = true;
                return true;
            }
            elseif ($this->try_reconnect)
            {
                if (@socket_connect($this->sock, $this->host, $this->port))
                {
                    $this->connected = true;
                    return true;
                }
            }
        }
        $this->set_error();
        trigger_error("connect server[{$this->host}:{$this->port}] fail. Error: {$this->errMsg}[{$this->errCode}].");
        return false;
    }
830879
public function connectTcp($host, $port)
    {
        $this->type = 'tcp';
        $pton = @inet_pton($host);
        $fd = null;
        if ($pton === false) { // dirty check
            \PHPDaemon\Clients\DNS\Pool::getInstance()->resolve($this->host, function ($result) use ($host, $port) {
                if (!$result) {
                    Daemon::log(get_class($this) . '->connectTcp : unable to resolve hostname: ' . $host);
                    $this->onStateEv($this->bev, \EventBufferEvent::ERROR);
                    return;
                }
                // @todo stack of addrs
                if (is_array($result)) {
                    if (!sizeof($result)) {
                        return;
                    }
                    srand(Daemon::$process->getPid());
                    $real = $result[rand(0, sizeof($result) - 1)];
                    srand();
                } else {
                    $real = $result;
                }
                $this->connectTcp($real, $port);
            });
            return true;
        }
        $this->hostReal = $host;
        if ($this->host === null) {
            $this->host = $this->hostReal;
        }
        // TCP
        $l = mb_orig_strlen($pton);
        if ($l === 4) {
            $this->addr = $host . ':' . $port;
            if (!$this->bevConnectEnabled) {
                $fd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            }
        } elseif ($l === 16) {
            $this->addr = '[' . $host . ']:' . $port;
            if (!$this->bevConnectEnabled) {
                $fd = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP);
            }
        } else {
            return false;
        }
        if (!$this->bevConnectEnabled && !$fd) {
            return false;
        }
        if (!$this->bevConnectEnabled) {
            socket_set_nonblock($fd);
        }
        if (!$this->bevConnectEnabled) {
            $this->fd = $fd;
            $this->setTimeouts(
                $this->timeoutRead !== null ? $this->timeoutRead : $this->timeout,
                $this->timeoutWrite !== null ? $this->timeoutWrite : $this->timeout
            );
            socket_connect($fd, $host, $port);
            socket_getsockname($fd, $this->locAddr, $this->locPort);
        } else {
            $this->bevConnect = true;
        }
        $this->setFd($fd);
        if (!$this->bev) {
            return false;
        }
        return true;
    }
1291868
public function connect($host, $port = 80, $secure = false)
    {
        // If the URI should be accessed via SSL, prepend the Hostname with ssl://
        $host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;

        // If we are connected to the wrong host, disconnect first
        if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
            if (is_resource($this->socket)) { $this->close();
            }
        }

        // Now, if we are not connected, connect
        if (! is_resource($this->socket) || ! $this->config['keepalive']) {
            $context = stream_context_create();
            if ($secure) {
                if ($this->config['sslcert'] !== null) {
                    if (! stream_context_set_option(
                        $context, 'ssl', 'local_cert',
                        $this->config['sslcert']
                    )
                    ) {
                        include_once 'Zend/Http/Client/Adapter/Exception.php';
                        throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
                    }
                }
                if ($this->config['sslpassphrase'] !== null) {
                    if (! stream_context_set_option(
                        $context, 'ssl', 'passphrase',
                        $this->config['sslpassphrase']
                    )
                    ) {
                        include_once 'Zend/Http/Client/Adapter/Exception.php';
                        throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
                    }
                }
            }

            $flags = STREAM_CLIENT_CONNECT;
            if ($this->config['persistent']) { $flags |= STREAM_CLIENT_PERSISTENT;
            }
            
            $this->socket = @stream_socket_client(
                $host . ':' . $port,
                $errno,
                $errstr,
                (int) $this->config['timeout'],
                $flags,
                $context
            );
            if (! $this->socket) {
                $this->close();
                include_once 'Zend/Http/Client/Adapter/Exception.php';
                throw new Zend_Http_Client_Adapter_Exception(
                    'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr
                );
            }

            // Set the stream timeout
            if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
                include_once 'Zend/Http/Client/Adapter/Exception.php';
                throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
            }

            // Update connected_to
            $this->connected_to = array($host, $port);
        }
    }
1160742
function Net_SSH1($host, $port = 22, $timeout = 10, $cipher = NET_SSH1_CIPHER_3DES)
    {
        $this->protocol_flags = array(
            1  => 'NET_SSH1_MSG_DISCONNECT',
            2  => 'NET_SSH1_SMSG_PUBLIC_KEY',
            3  => 'NET_SSH1_CMSG_SESSION_KEY',
            4  => 'NET_SSH1_CMSG_USER',
            9  => 'NET_SSH1_CMSG_AUTH_PASSWORD',
            10 => 'NET_SSH1_CMSG_REQUEST_PTY',
            12 => 'NET_SSH1_CMSG_EXEC_SHELL',
            13 => 'NET_SSH1_CMSG_EXEC_CMD',
            14 => 'NET_SSH1_SMSG_SUCCESS',
            15 => 'NET_SSH1_SMSG_FAILURE',
            16 => 'NET_SSH1_CMSG_STDIN_DATA',
            17 => 'NET_SSH1_SMSG_STDOUT_DATA',
            18 => 'NET_SSH1_SMSG_STDERR_DATA',
            19 => 'NET_SSH1_CMSG_EOF',
            20 => 'NET_SSH1_SMSG_EXITSTATUS',
            33 => 'NET_SSH1_CMSG_EXIT_CONFIRMATION'
        );

        $this->_define_array($this->protocol_flags);

        $this->fsock = @fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$this->fsock) {
            user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"), E_USER_NOTICE);
            return;
        }

        $this->server_identification = $init_line = fgets($this->fsock, 255);

        if (defined('NET_SSH1_LOGGING')) {
            $this->protocol_flags_log[] = '<-';
            $this->protocol_flags_log[] = '->';

            if (NET_SSH1_LOGGING == NET_SSH1_LOG_COMPLEX) {
                $this->message_log[] = $this->server_identification;
                $this->message_log[] = $this->identifier . "\r\n";
            }
        }

        if (!preg_match('#SSH-([0-9\.]+)-(.+)#', $init_line, $parts)) {
            user_error('Can only connect to SSH servers', E_USER_NOTICE);
            return;
        }
        if ($parts[1][0] != 1) {
            user_error("Cannot connect to SSH $parts[1] servers", E_USER_NOTICE);
            return;
        }

        fputs($this->fsock, $this->identifier."\r\n");

        $response = $this->_get_binary_packet();
        if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) {
            user_error('Expected SSH_SMSG_PUBLIC_KEY', E_USER_NOTICE);
            return;
        }

        $anti_spoofing_cookie = $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 8);

        $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);

        $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
        $server_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
        $this->server_key_public_exponent = $server_key_public_exponent;

        $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
        $server_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
        $this->server_key_public_modulus = $server_key_public_modulus;

        $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);

        $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
        $host_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
        $this->host_key_public_exponent = $host_key_public_exponent;

        $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
        $host_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
        $this->host_key_public_modulus = $host_key_public_modulus;

        $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);

        // get a list of the supported ciphers
        extract(unpack('Nsupported_ciphers_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)));
        foreach ($this->supported_ciphers as $mask=>$name) {
            if (($supported_ciphers_mask & (1 << $mask)) == 0) {
                unset($this->supported_ciphers[$mask]);
            }
        }

        // get a list of the supported authentications
        extract(unpack('Nsupported_authentications_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)));
        foreach ($this->supported_authentications as $mask=>$name) {
            if (($supported_authentications_mask & (1 << $mask)) == 0) {
                unset($this->supported_authentications[$mask]);
            }
        }

        $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie));

        $session_key = '';
        for ($i = 0; $i < 32; $i++) {
            $session_key.= chr(crypt_random(0, 255));
        }
        $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0));

        if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) {
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $server_key_public_exponent,
                    $server_key_public_modulus
                )
            );
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $host_key_public_exponent,
                    $host_key_public_modulus
                )
            );
        } else {
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $host_key_public_exponent,
                    $host_key_public_modulus
                )
            );
            $double_encrypted_session_key = $this->_rsa_crypt(
                $double_encrypted_session_key,
                array(
                    $server_key_public_exponent,
                    $server_key_public_modulus
                )
            );
        }

        $cipher = isset($this->supported_ciphers[$cipher]) ? $cipher : NET_SSH1_CIPHER_3DES;
        $data = pack('C2a*na*N', NET_SSH1_CMSG_SESSION_KEY, $cipher, $anti_spoofing_cookie, 8 * strlen($double_encrypted_session_key), $double_encrypted_session_key, 0);

        if (!$this->_send_binary_packet($data)) {
            user_error('Error sending SSH_CMSG_SESSION_KEY', E_USER_NOTICE);
            return;
        }

        switch ($cipher) {
            //case NET_SSH1_CIPHER_NONE:
            //    $this->crypto = new Crypt_Null();
            //    break;
            case NET_SSH1_CIPHER_DES:
                $this->crypto = new Crypt_DES();
                $this->crypto->disablePadding();
                $this->crypto->enableContinuousBuffer();
                $this->crypto->setKey(substr($session_key, 0,  8));
                break;
            case NET_SSH1_CIPHER_3DES:
                $this->crypto = new Crypt_TripleDES(CRYPT_DES_MODE_3CBC);
                $this->crypto->disablePadding();
                $this->crypto->enableContinuousBuffer();
                $this->crypto->setKey(substr($session_key, 0, 24));
                break;
            //case NET_SSH1_CIPHER_RC4:
            //    $this->crypto = new Crypt_RC4();
            //    $this->crypto->enableContinuousBuffer();
            //    $this->crypto->setKey(substr($session_key, 0,  16));
            //    break;
        }

        $response = $this->_get_binary_packet();

        if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
            user_error('Expected SSH_SMSG_SUCCESS', E_USER_NOTICE);
            return;
        }

        $this->bitmap = NET_SSH1_MASK_CONSTRUCTOR;
    }
43751
def requestSocket(self, host, port):
        '''
        
        '''
        socket = self._context.socket(zmq.REQ)
        socket.connect(self.tcpAddress(host, port))
        return socket
1080044
public static function ping(string $host, int $port, int $timeout = 5): bool
    {
        if ($fp = @fsockopen($host, $port, $errCode, $errStr, $timeout)) {
            fclose($fp);
            return true;
        }
        return false;
    }
446331
public function connect($host = null, $port = null)
    {
        return $this->driver->connect(
            $host ? $host : $this->host,
            $port ? $port : $this->port
        );
    }
496231
public function connect($host = '127.0.0.1', $port = 21)
	{
		$errno = null;
		$err   = null;

		// If already connected, return
		if (\is_resource($this->conn))
		{
			return true;
		}

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			$this->conn = @ftp_connect($host, $port, $this->timeout);

			if ($this->conn === false)
			{
				throw new FilesystemException(sprintf('%1$s: Could not connect to host " %2$s " on port " %3$s "', __METHOD__, $host, $port));
			}

			// Set the timeout for this connection
			ftp_set_option($this->conn, FTP_TIMEOUT_SEC, $this->timeout);

			return true;
		}

		// Connect to the FTP server.
		$this->conn = @ fsockopen($host, $port, $errno, $err, $this->timeout);

		if (!$this->conn)
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Could not connect to host " %2$s " on port " %3$s ". Socket error number: %4$s and error message: %5$s',
					__METHOD__,
					$host,
					$port,
					$errno,
					$err
				)
			);
		}

		// Set the timeout for this connection
		socket_set_timeout($this->conn, $this->timeout, 0);

		// Check for welcome response code
		if (!$this->_verifyResponse(220))
		{
			throw new FilesystemException(sprintf('%1$s: Bad response. Server response: %2$s [Expected: 220]', __METHOD__, $this->response));
		}

		return true;
	}
197277
public function open($host, $port, $timeout)
    {
        if (($this->socket = @fsockopen($host, $port, $errno, $errstr, ($timeout / 1000))) === false) {
            return false;
        }

        return true;
    }
241223
public function connect($host,$domain)
    {
        $remoteSocket = $host . ':' . $this->config['port'];
        $this->domain = $domain;
        $errnum       = 0;
        $errstr       = '';
        $this->host   = $remoteSocket;
        // open connection

        $this->socket = @stream_socket_client(
            $this->host,
            $errnum,
            $errstr,
            $this->timeout,
            STREAM_CLIENT_CONNECT,
            stream_context_create($this->validationOptions['context'])
        );

        // connected?
        if (!$this->isConnect()) {
            return 'no connection';
        }

        $result = stream_set_timeout($this->socket, $this->timeout);

        if (!$result) {
            return 'Cannot set timeout';
        }
        return 'connected';
    }
1292402
public function recv($timeout = null)
    {
        // timeout specified?
        if ($timeout !== null) {
            stream_set_timeout($this->socket, $timeout);
        }
        // retrieve response
        $line = fgets($this->socket, 1024);

        if ($this->validationOptions['debug'] === true) {
            $this->debug[] = ["timestamp" => microtime(true), "message" => "received> {$line}"];
        }

        // have we timed out?
        $info = stream_get_meta_data($this->socket);
        if (!empty($info['timed_out'])) {
            throw new Exception\ExceptionTimeout('Timed out in recv');
        }
        // did we actually receive anything?
        if ($line === false) {
            throw new Exception\ExceptionNoResponse('No response in recv');
        }

        return $line;
    }
1184638
public static function create($host, $port)
  {
    $transceiver = new NettyFramedSocketTransceiver();
    $transceiver->createSocket($host, $port);
    
    return $transceiver;
  }
433600
public Socket getSocket(String host, int port, boolean useSecureSocket, SecurityDomain securityDomain) throws Exception {
		return getSocket(host,port,useSecureSocket,securityDomain,null);
	}