PHPDaemon\Network\Connection::connectUdp PHP Method

connectUdp() public method

Establish UDP connection
public connectUdp ( string $host, integer $port ) : boolean
$host string Hostname
$port integer Port
return boolean Success
    public function connectUdp($host, $port)
    {
        $this->type = 'udp';
        $pton = @inet_pton($host);
        if ($pton === false) {
            // dirty check
            \PHPDaemon\Clients\DNS\Pool::getInstance()->resolve($host, function ($result) use($host, $port) {
                if (!$result) {
                    Daemon::log(get_class($this) . '->connectUdp : unable to resolve hostname: ' . $host);
                    $this->onStateEv($this->bev, \EventBufferEvent::ERROR);
                    return;
                }
                // @todo stack of addrs
                if (is_array($result)) {
                    srand(Daemon::$process->getPid());
                    $real = $result[rand(0, sizeof($result) - 1)];
                    srand();
                } else {
                    $real = $result;
                }
                $this->connectUdp($real, $port);
            });
            return true;
        }
        $this->hostReal = $host;
        if ($this->host === null) {
            $this->host = $this->hostReal;
        }
        $l = mb_orig_strlen($pton);
        if ($l === 4) {
            $this->addr = $host . ':' . $port;
            /* @TODO: use EventUtil::SOCK_DGRAM */
            $fd = socket_create(\EventUtil::AF_INET, SOCK_DGRAM, \EventUtil::SOL_UDP);
        } elseif ($l === 16) {
            $this->addr = '[' . $host . ']:' . $port;
            $fd = socket_create(\EventUtil::AF_INET6, SOCK_DGRAM, \EventUtil::SOL_UDP);
        } else {
            return false;
        }
        if (!$fd) {
            return false;
        }
        socket_set_nonblock($fd);
        @socket_connect($fd, $host, $port);
        socket_getsockname($fd, $this->locAddr, $this->locPort);
        $this->setFd($fd);
        if (!$this->bev) {
            return false;
        }
        return true;
    }