PHPDaemon\Network\Connection::connectTcp PHP Method

connectTcp() public method

Establish TCP connection
public connectTcp ( string $host, integer $port ) : boolean
$host string Hostname
$port integer Port
return boolean Success
    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;
    }