mSocket = false; } public function __destruct() { $this->fini_socket(); } public static function instance() { if(self::$stInstance == null) { self::$stInstance = new tcp_client(); } return self::$stInstance; } public function get_words($word) { $times = 0; do { if($this->init_socket() == false) { return false; } $param = array("type" => self::GetRelatedWord, "keyword" => $word); $ret = $this->write_param($param); if($ret === false) { $this->fini_socket(); } } while($ret == false && ++$times < 2); if($ret == true) { $body = $this->read_body(); if($body != false) { return unserialize($body); } } $this->fini_socket(); return false; } public function get_result($params) { if($this->init_socket() == false) { return false; } $param = array("type" => self::SearchReasult, "params" => $params); $ret = $this->write_param($param); if($ret == true) { $body = $this->read_body(); if($body != false) { return unserialize($body); } } $this->fini_socket(); return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private function init_socket() { if($this->mSocket != false) { if(feof($this->mSocket) == true) { $this->fini_socket(); } else { return true; } } else { $host = $this->remote_addr(); $this->mSocket = stream_socket_client ($host,$err,$errno,30); if($this->mSocket == false) { socket_set_timeout($this->mSocket,self::time_out); Log::record("connect search server err --- code:{$errno} : {$err}"); return false; } else { return true; } } } private function fini_socket() { if($this->mSocket != false) { stream_socket_shutdown($this->mSocket,STREAM_SHUT_RDWR); fclose($this->mSocket); $this->mSocket = false; } } private function read_body() { $body_len = $this->read(self::body_header_len); $body_len = intval($body_len); if($body_len > 0) { $body = $this->read($body_len); return $body; } else { return false; } } private function read($len) { $left = $len; $data = ""; while ($left > 0) { if(feof($this->mSocket) == true) { return false; } else { $tmp = fread($this->mSocket,$left); $left = $left - strlen($tmp); $data .= $tmp; } } return $data; } private function write($data,$len) { while ($len > 0) { $ret = fwrite($this->mSocket,$data); if($ret == false || $ret <= 0) { return false; } else { $len -= $ret; } } return true; } private function write_param($param) { $param = serialize($param); $len = sprintf("%010d",strlen($param)); $data = $len . $param; return $this->write($data,strlen($data)); } private function remote_addr() { global $config; $host = $config['searcher']['host']; $port = $config['searcher']['port']; return "{$host}:{$port}"; } }