您好,欢迎访问一九零五行业门户网

很简单的一个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(); }}
复制代码
很简单, socket, php
其它类似信息

推荐信息