PHP Socket FETCH Data class

Source: Internet
Author: User

<?PHPDefine("CONNECTED",true);Define("Disconnected",false);/** * Socket class * * * @author ZT*/Classsocket{Private Static $instance; Private $connection=NULL; Private $connectionState=disconnected; Private $defaultHost= "127.0.0.1"; Private $defaultPort= 80; Private $defaultTimeout= 20;  Public  $debug=false; function__construct () {}/** * Singleton pattern. Returns the same instance to all callers * * @return Socket*/     Public Static functionSingleton () {if(Self::$instance==NULL|| ! Self::$instanceinstanceof Socket) { Self::$instance=NewSocket (); }        returnSelf::$instance; }    /** * Connects to the socket with the given address and port * * @return void*/     Public functionConnect$serverHost=false,$serverPort=false,$timeOut=false)    {                if($serverHost==false)        {            $serverHost=$this-Defaulthost; }                if($serverPort==false)        {            $serverPort=$this-Defaultport; }        $this->defaulthost =$serverHost; $this->defaultport =$serverPort; if($timeOut==false)        {            $timeOut=$this-defaulttimeout; }        $this->connection = Socket_create (Af_inet,sock_stream,sol_tcp); if(Socket_connect ($this->connection,$serverHost,$serverPort) ==false)        {            $errorString= Socket_strerror (Socket_last_error ($this-connection)); $this->_throwerror ("Connecting to {$serverHost}:{$serverPort} Failed.<br>reason: {$errorString}"); }Else{            $this->_throwmsg ("Socket connected!"); }                $this->connectionstate =CONNECTED; }        /** * disconnects from the server * * @return True on succes, False if the connection is already closed */     Public functionDisconnect () {if($this-validateconnection ()) {Socket_close ($this-connection); $this->connectionstate =disconnected; $this->_throwmsg ("Socket disconnected!"); return true; }        return false; }    /** * sends a command to the server * * @return String Server response*/     Public functionSendRequest ($command)    {        if($this-validateconnection ()) {            $result= Socket_write ($this->connection,$command,strlen($command)); return $result; }        $this->_throwerror ("sending command \" {$command}\ "Failed.<br>reason:not Connected"); }                 Public functionIsconn () {return $this-ConnectionState; }             Public functiongetunreadbytes () {$info=Socket_get_status($this-connection); return $info[' Unread_bytes ']; }         Public functionGetconnname (&$addr, &$port)    {        if($this-validateconnection ()) {Socket_getsockname ($this->connection,$addr,$port); }    }               /** * Gets the server response (not multilined) * * @return String Server response*/     Public functionGetResponse () {$read _set=Array($this-connection);  while(($events= Socket_select ($read _set,$write _set=NULL,$exception _set=NULL, 0))!==false)         {            if($events> 0)            {                foreach($read _set  as $so)                {                    if(!Is_resource($so))                    {                        $this->_throwerror ("Receiving response from server Failed.<br>reason:not connected"); return false; }ElseIf( ($ret= @socket_read ($so, 4096,php_binary_read)) = =false){                        $this->_throwerror ("Receiving response from server Failed.<br>reason:not bytes to read"); return false; }                    return $ret; }            }        }                return false; }     Public functionwaitForResponse () {if($this-validateconnection ()) {            $socketResponse= "";  while($val= Socket_read ($this->connection, 1024)){                $socketResponse.=$val; }            return $socketResponse; }                $this->_throwerror ("Receiving response from server Failed.<br>reason:not connected"); return false; }    /** * Validates the connection state * * @return BOOL*/    Private functionvalidateconnection () {return(Is_resource($this->connection) && ($this->connectionstate! =disconnected)); }    /** * Throws an error * * @return void*/    Private function_throwerror ($errorMessage)    {        Echo"Socket Error:".$errorMessage; }    /** * Throws an message * * @return void*/    Private function_throwmsg ($msg)    {        if($this-Debug) {            Echo"Socket message:".$msg. "\ n"; }    }    /** * If There still was a connection alive, disconnect it*/     Public function__destruct () {$this-disconnect (); }}

Read data using the waitForResponse () method

Example code:

functionSend_socket ($req,$ip,$port){    $byte=NewBytes (); $req _bytes=$byte->getbytes ($req); $req _trans=$byte-&GT;TOSTR ($req _bytes); $req _length=strlen($req _trans); $pack=Pack("a{$req _length}",$req _trans); $socket= Socket::Singleton (); $socket->connect ($ip,$port); $socket->sendrequest ($pack); $socket _result=$socket-waitForResponse (); $socket-disconnect (); return $socket _result;}Var_dump(Send_socket ("Test", "127.0.0.1", 443));

PHP Socket FETCH Data class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.