PHP 5, you need to open the socket extension
- //socke operation class
- class Socket {
- private $host;//the host connected to the socket
- private $port;//the port number of the socket
- private $error=array() ;
- private $socket=null;//The connection identifier of the socket
- private $queryStr="";//The data sent
- public function __construct($host,$port) {
- if(!extension_loaded("sockets")) {
- exit("Please open the socket extension");
- }
- if(empty($host)) exit("Please enter the target address");
- if(empty($port)) exit("Please enter a valid port No.");
- $this->host=$host;
- $this->port=$port;
- $this->CreateSocket();//Create connection
- }
-
- //Create socket
- private function CreateSocket(){
- !$this->socket&&$this->socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);//Create socket
- $r=@socket_connect($this->socket,$this- >host,$this->port);
- if($r){
- return $r;
- }else{
- $this->error[]=socket_last_error($this->socket);
- return false;
- }
- }
-
- //Write data to the socket server and read
- 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;
- }
-
-
- //Filter the sent data
- private function filterSendData($contents){
- //Process the written data
- return $contents;
- }
-
-
- //All error messages
- public function getError(){
- return $this->error;
- }
-
- //Last error message
- public function getLastError(){
- return $this->error(count($this->error));
- }
- //Get the last message sent
- public function getLastMsg(){
- return $this->queryStr;
- }
-
- public function getHost(){
- return $this->host;
- }
-
- public function getPort(){
- return $this->port;
- }
-
- //Close the socket connection
- private function close(){
- $this->socket&&socket_close($this->socket);//Close Connection
- $this->socket=null;//Connection resource initialization
- }
-
- public function __destruct(){
- $this->close();
- }
- }
Copy code
|