Php socket資料編碼

來源:互聯網
上載者:User
bytes.php 位元組編碼類別

/** * byte數組與字串轉化類 * @author  * created on 2011-7-15 */class bytes {       /**     * 轉換一個string字串為byte數組     * @param $str 需要轉換的字串     * @param $bytes 目標byte數組     * @author zikie     */        public static function getbytes($str) {        $len = strlen($str);        $bytes = array();           for($i=0;$i<$len;$i++) {               if(ord($str[$i]) >= 128){                   $byte = ord($str[$i]) - 256;               }else{                   $byte = ord($str[$i]);               }            $bytes[] =  $byte ;        }        return $bytes;    }       /**     * 將位元組數組轉化為string類型的資料     * @param $bytes 位元組數組     * @param $str 目標字串     * @return 一個string類型的資料     */        public static function tostr($bytes) {        $str = '';        foreach($bytes as $ch) {            $str .= chr($ch);        }           return $str;    }       /**     * 轉換一個int為byte數組     * @param $byt 目標byte數組     * @param $val 需要轉換的字串     * @author zikie     */       public static function integertobytes($val) {        $byt = array();        $byt[0] = ($val & 0xff);        $byt[1] = ($val >> 8 & 0xff);        $byt[2] = ($val >> 16 & 0xff);        $byt[3] = ($val >> 24 & 0xff);        return $byt;    }       /**     * 從位元組數組中指定的位置讀取一個integer類型的資料     * @param $bytes 位元組數組     * @param $position 指定的開始位置     * @return 一個integer類型的資料     */        public static function bytestointeger($bytes, $position) {        $val = 0;        $val = $bytes[$position + 3] & 0xff;        $val <<= 8;        $val |= $bytes[$position + 2] & 0xff;        $val <<= 8;        $val |= $bytes[$position + 1] & 0xff;        $val <<= 8;        $val |= $bytes[$position] & 0xff;        return $val;    }    /**     * 轉換一個shor字串為byte數組     * @param $byt 目標byte數組     * @param $val 需要轉換的字串     * @author zikie     */       public static function shorttobytes($val) {        $byt = array();        $byt[0] = ($val & 0xff);        $byt[1] = ($val >> 8 & 0xff);        return $byt;    }       /**     * 從位元組數組中指定的位置讀取一個short類型的資料。     * @param $bytes 位元組數組     * @param $position 指定的開始位置     * @return 一個short類型的資料     */        public static function bytestoshort($bytes, $position) {        $val = 0;        $val = $bytes[$position + 1] & 0xff;        $val = $val << 8;        $val |= $bytes[$position] & 0xff;        return $val;    }   }

socket.class.php socket賦值類

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.
Reason: {$errorString}"); }else{ $this->_throwMsg("Socket connected!"); } $this->connectionState = CONNECTED; } /** * Disconnects from the server * * @return True on succes, false if the connection was already closed */ public function disconnect() { 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 function sendRequest($command) { if($this->validateConnection()) { $result = socket_write($this->connection,$command,strlen($command)); return $result; } $this->_throwError("Sending command \"{$command}\" failed.
Reason: Not connected"); } public function isConn() { return $this->connectionState; } public function getUnreadBytes() { $info = socket_get_status($this->connection); return $info['unread_bytes']; } public function getConnName(&$addr, &$port) { if ($this->validateConnection()) { socket_getsockname($this->connection,$addr,$port); } } /** * Gets the server response (not multilined) * * @return string Server response */ public function getResponse() { $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.
Reason: Not connected"); return false; }elseif ( ( $ret = @socket_read($so,4096,PHP_BINARY_READ) ) == false){ $this->_throwError("Receiving response from server failed.
Reason: Not bytes to read"); return false; } return $ret; } } } return false; } public function waitForResponse() { if($this->validateConnection()) { return socket_read($this->connection, 2048); } $this->_throwError("Receiving response from server failed.
Reason: Not connected"); return false; } /** * Validates the connection state * * @return bool */ private function validateConnection() { 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\n"; } } /** * If there still was a connection alive, disconnect it */ public function __destruct() { $this->disconnect(); }}?>

PacketBase.class.php 打包類

 *  */class PacketBase extends ContentHandler{    private $head;    private $params;    private $opcode;    /**************************construct***************************/    function __construct()    {        $num = func_num_args();        $args = func_get_args();        switch($num){                case 0:                    //do nothing 用來產生對象的                break;                case 1:                        $this->__call('__construct1', $args);                        break;                case 2:                        $this->__call('__construct2', $args);                        break;                default:                        throw new Exception();        }    }    //無參數    public function __construct1($OPCODE)    {            $this->opcode = $OPCODE;            $this->params = 0;    }    //有參數    public function __construct2($OPCODE,  $PARAMS)    {            $this->opcode = $OPCODE;            $this->params = $PARAMS;    }    //析構    function __destruct()    {        unset($this->head);        unset($this->buf);    }        //打包    public function pack()    {        $head = $this->MakeHead($this->opcode,$this->params);        return $head.$this->buf;    }    //解包    public function unpack($packet,$noHead = false)    {                $this->buf = $packet;        if (!$noHead){        $recvHead = unpack("S2hd/I2pa",$packet);        $SD = $recvHead[hd1];//SD        $this->contentlen = $recvHead[hd2];//content len        $this->opcode = $recvHead[pa1];//opcode        $this->params = $recvHead[pa2];//params                $this->pos = 12;//去除包頭長度                if ($SD != 21316)        {            return false;        }        }else         {            $this->pos = 0;        }        return true;       }    public function GetOP()    {        if ($this->buf)        {            return $this->opcode;        }        return 0;    }    /************************private***************************/    //構造包頭    private function MakeHead($opcode,$param)    {        return pack("SSII","SD",$this->TellPut(),$opcode,$param);    }        //用以類比函數重載    private function __call($name, $arg)    {        return call_user_func_array(array($this, $name), $arg);    }            /***********************Uitl***************************/    //將16進位的op轉成10進位    static function MakeOpcode($MAJOR_OP, $MINOR_OP)    {        return ((($MAJOR_OP & 0xffff) << 16) | ($MINOR_OP & 0xffff));    }}/** * 包體類 * 包含了對包體的操作 */class ContentHandler{    public $buf;    public $pos;    public $contentlen;//use for unpack        function __construct()    {        $this->buf = "";        $this->contentlen = 0;        $this->pos = 0;    }    function __destruct()    {        unset($this->buf);    }        public function PutInt($int)    {        $this->buf .= pack("i",(int)$int);    }    public function PutUTF($str)    {        $l = strlen($str);        $this->buf .= pack("s",$l);        $this->buf .= $str;    }    public function PutStr($str)    {        return $this->PutUTF($str);    }            public function TellPut()    {        return strlen($this->buf);    }            /*******************************************/        public function GetInt()    {        //$cont = substr($out,$l,4);        $get = unpack("@".$this->pos."/i",$this->buf);        if (is_int($get[1])){            $this->pos += 4;            return $get[1];        }        return 0;    }      public function GetShort()    {        $get = unpack("@".$this->pos."/S",$this->buf);        if (is_int($get[1])){            $this->pos += 2;            return $get[1];        }        return 0;    }    public function GetUTF()    {        $getStrLen = $this->GetShort();                if ($getStrLen > 0)        {            $end = substr($this->buf,$this->pos,$getStrLen);            $this->pos += $getStrLen;            return $end;        }        return '';    }    /***************************/      public function GetBuf()    {        return $this->buf;    }        public function SetBuf($strBuf)    {        $this->buf = $strBuf;    }        public function ResetBuf(){        $this->buf = "";        $this->contentlen = 0;        $this->pos = 0;    }}?>

格式

struct header{int type;     // 訊息類型int length;     // 訊息長度}struct MSG_Q2R2DB_PAYRESULT{int serialno; int openid; char payitem[512];int billno; int zoneid;int providetype;  int coins; }調用的方法,另外需require兩個php檔案,一個是位元組編碼類別,另外一個socket封裝類,其實主要看位元組編碼類別就可以了!

調用測試

public function index() {        $socketAddr = "127.0.0.1";            $socketPort = "10000";            try {                        $selfPath = dirname ( __FILE__ );            require ($selfPath . "/../Tool/Bytes.php");            $bytes = new Bytes ();                        $payitem = "sdfasdfasdfsdfsdfsdfsdfsdfsdf";            $serialno = 1;            $zoneid = 22;            $openid = "CFF47C448D4AA2069361567B6F8299C2";                        $billno = 1;            $providetype = 1;            $coins = 1;                        $headType = 10001;            $headLength = 56 + intval(strlen($payitem ));                        $headType = $bytes->integerToBytes ( intval ( $headType ) );            $headLength = $bytes->integerToBytes ( intval ( $headLength ) );            $serialno = $bytes->integerToBytes ( intval ( $serialno ) );            $zoneid = $bytes->integerToBytes ( intval ( $zoneid ) );            $openid = $bytes->getBytes( $openid  );            $payitem_len = $bytes->integerToBytes ( intval ( strlen($payitem) ) );            $payitem =  $bytes->getBytes($payitem);                        $billno = $bytes->integerToBytes ( intval ( $billno ) );            $providetype = $bytes->integerToBytes ( intval ( $providetype ) );            $coins = $bytes->integerToBytes ( intval ( $coins ) );                        $return_betys = array_merge ($headType , $headLength , $serialno , $zoneid , $openid,$payitem_len ,$payitem,$billno,$providetype,$coins);                        $msg = $bytes->toStr ($return_betys);            $strLen = strlen($msg);            $packet = pack("a{$strLen}", $msg);            $pckLen = strlen($packet);                        $socket = Socket::singleton ();            $socket->connect ( $socketAddr, $socketPort ); //連伺服器                        $sockResult = $socket->sendRequest ( $packet); // 將包發送給伺服器             sleep ( 3 );            $socket->disconnect (); //關閉連結        } catch ( Exception $e ) {            var_dump($e);            $this->log_error("pay order send to server".$e->getMessage());        }    }
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.