A very simple socket client PHP class
Release: 2016-07-25 08:42:28
Original
977 people have browsed it
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
|
Very simple, socket, PHP
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31