很簡單的一個socket客戶端PHP類
php 5,需要打開socket擴展
//socke操作類 class Socket { private $host;//連接socket的主機 private $port;//socket的端口號 private $error=array(); private $socket=null;//socket的連接標識 private $queryStr="";//發送的數據 public function __construct($host,$port) { if(!extension_loaded("sockets")){ exit("請打開socket擴展 "); } if(empty($host)) exit("請輸入目標地址"); if(empty($port)) exit("請輸入有效的端口號"); $this->host=$host; $this->port=$port; $this->CreateSocket();//創建連接
}//創建socket private function CreateSocket(){ !$this->socket&&$this->socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);//創建socket $r=@socket_connect($this->socket,$this->host,$this->port); if($r){ return $r; }else{ $this->error[]=socket_last_error($this->socket); return false; } } //向socket服務器寫入數據并讀取 public function wr($contents){ $this->queryStr=""; $this->queryStr=$contents; !$this->socket&&$this->CreateSocket(); $contents=$this->fliterSendData($contents); $result=socket_write($this->socket,$contents,strlen($contents)); if(!intval($result)){ $this->error[]=socket_last_error($this->socket); return false; } $response=socket_read($this->socket,12048); if(false===$response){ $this->error[]=socket_last_error($this->socket); return false; } return $response; } //對發送的數據進行過濾 private function fliterSendData($contents){ //對寫入的數據進行處理 return $contents; } //所有錯誤信息 public function getError(){ return $this->error; } //最后一次錯誤信息 public function getLastError(){ return $this->error(count($this->error)); } //獲取最后一次發送的消息 public function getLastMsg(){ return $this->queryStr; } public function getHost(){ return $this->host; } public function getPort(){ return $this->port; } //關閉socket連接 private function close(){ $this->socket&&socket_close($this->socket);//關閉連接 $this->socket=null;//連接資源初始化 } public function __destruct(){ $this->close(); }
}</pre>
本文由用戶 pphe 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!