Swoole\Client\TCP::connect PHP Method

connect() public method

连接到服务器 接受一个浮点型数字作为超时,整数部分作为sec,小数部分*100万作为usec
public connect ( string $host, integer $port, float $timeout = 0.1, $nonblock = false ) : boolean
$host string 服务器地址
$port integer 服务器地址
$timeout float 超时默认值,连接,发送,接收都使用此设置
return boolean
    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;
    }

Usage Example

Example #1
0
 /**
  * Connect client to server
  * @param $timeout
  * @return $this
  */
 public function connect($timeout = 0.5)
 {
     if (extension_loaded('swoole')) {
         $this->socket = new \swoole_client(SWOOLE_SOCK_TCP);
     } else {
         $this->socket = new TCP();
     }
     //建立连接
     if (!$this->socket->connect($this->host, $this->port, $timeout)) {
         return false;
     }
     $this->connected = true;
     //WebSocket握手
     if ($this->socket->send($this->createHeader()) === false) {
         return false;
     }
     $headerBuffer = '';
     while (true) {
         $_tmp = $this->socket->recv();
         if ($_tmp) {
             $headerBuffer .= $_tmp;
             if (substr($headerBuffer, -4, 4) != "\r\n\r\n") {
                 continue;
             }
         } else {
             return false;
         }
         return $this->doHandShake($headerBuffer);
     }
     return false;
 }
All Usage Examples Of Swoole\Client\TCP::connect