/** * 连接到服务器 * @param SOA_Result $retObj * @return bool * @throws \Exception */ protected function connectToServer(SOA_Result $retObj) { $ret = false; //循环连接 while (count($this->servers) > 0) { $svr = $this->getServer(); //基于Swoole扩展 if ($this->haveSwoole) { $key = $svr['host'] . ':' . $svr['port'] . '-' . $retObj->index; $socket = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP, SWOOLE_SOCK_SYNC, $key); $socket->set(array('open_length_check' => true, 'package_max_length' => $this->packet_maxlen, 'package_length_type' => 'N', 'package_body_offset' => RPCServer::HEADER_SIZE, 'package_length_offset' => 0)); /** * 尝试重连一次 */ for ($i = 0; $i < 2; $i++) { $ret = $socket->connect($svr['host'], $svr['port'], $this->timeout); if ($ret === false and ($socket->errCode == 114 or $socket->errCode == 115)) { //强制关闭,重连 $socket->close(true); continue; } else { break; } } $socketFd = $socket->sock; } elseif ($this->haveSockets) { $socket = new TCP(); $socket->try_reconnect = false; $ret = $socket->connect($svr['host'], $svr['port'], $this->timeout); $socketFd = intval($socket->getSocket()); } else { $socket = new Stream(); $ret = $socket->connect($svr['host'], $svr['port'], $this->timeout); $socketFd = intval($socket->getSocket()); } //连接被拒绝,证明服务器已经挂了 //TODO 如果连接失败,需要上报机器存活状态 if ($ret === false and $socket->errCode == 111) { $this->onConnectServerFailed($svr); unset($socket); } else { $retObj->socket = $socket; $retObj->server_host = $svr['host']; $retObj->server_port = $svr['port']; //使用SOCKET的编号作为ID $retObj->id = $socketFd; break; } } return $ret; }