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;
}