Phpsocket data encoding

Source: Internet
Author: User
Phpsocket data encoding bytes. php byte encoding class

/*** Byte array and string conversion class * @ author * created on 2011-7-15 */class bytes {/*** convert a string to a byte array * @ param $ str to be converted * @ param $ bytes target byte array * @ 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;}/*** convert bytes Convert the array to string type data * @ param $ bytes byte array * @ param $ str target string * @ return a string type data */public static function tostr ($ bytes) {$ str = ''; foreach ($ bytes as $ ch) {$ str. = chr ($ ch);} return $ str ;} /*** convert an int to a byte array * @ param $ byt the destination byte array * @ param $ val the string to be converted * @ author zikie */public static function integertobytes ($ val) {$ byt = array (); $ byt [0] = ($ val & 0xff); $ byt [1] = ($ val> 8 & 0xff); $ B Yt [2] = ($ val> 16 & 0xff); $ byt [3] = ($ val> 24 & 0xff); return $ byt ;} /*** read an integer type data from the specified position in the byte array * @ param $ bytes byte array * @ param $ position specified start position * @ return an integer type data */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 ;} /*** convert a shor string to a byte array * @ param $ byt target byte array * @ param $ val the string to be converted * @ author zikie */public static function using tobytes ($ val) {$ byt = array (); $ byt [0] = ($ val & 0xff); $ byt [1] = ($ val> 8 & 0xff ); return $ byt;}/*** reads data of the short type from the specified position in the byte array. * @ Param $ bytes byte array * @ param $ position specifies the start position * @ return a short type data */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 assignment class

 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 strin G Server response */public function getResponse () {$ read_set = array ($ this-> connection); while ($ events = socket_select ($ read_set, $ write_set = NULL, $ prediction_set = NULL, 0 ))! = False) {if ($ events> 0) {foreach ($ read_set as $ so) {if (! Is_resource ($ so) {$ this-> _ throwError ("logging response from server failed.
Reason: Not connected "); return false;} elseif ($ ret = @ socket_read ($ so, 4096, PHP_BINARY_READ) = false) {$ this-> _ throwError ("processing ing 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 ("handling 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" ;}}/ *** If there still was a connection alive, disconnect it */public function _ destruct () {$ this-> disconne Ct () ;}}?>

PacketBase. class. php packaging class

 **/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 is used to generate the object's break; case 1: $ this->__ call ('_ construct1', $ args); break; case 2: $ this->__ call ('_ construct2', $ args ); break; default: thr Ow new Exception () ;}// no public function _ construct1 ($ OPCODE) {$ this-> opcode = $ OPCODE; $ this-> params = 0 ;} // public function _ construct2 ($ OPCODE, $ PARAMS) {$ this-> opcode = $ OPCODE; $ this-> params = $ PARAMS ;} // destructor function _ destruct () {unset ($ this-> head); unset ($ this-> buf);} // package public function pack () {$ head = $ this-> MakeHead ($ this-> opcode, $ this-> params); return $ head. $ this-> buf ;} // Unpack public function unpack ($ packet, $ noHead = false) {$ this-> buf = $ packet; if (! $ NoHead) {$ recvHead = unpack ("S2hd/I 2pa", $ packet); $ SD = $ recvHead [hd1]; // SD $ this-> contentlen = $ recvHead [hd2]; // content len $ this-> opcode = $ recvHead [pa1]; // opcode $ this-> params = $ recvHead [pa2]; // params $ this-> pos = 12; // remove the header length if ($ SD! = 21316) {return false ;}} else {$ this-> pos = 0;} return true;} public function GetOP () {if ($ this-> buf) {return $ this-> opcode;} return 0 ;} /************************ private ************** ************ // Construct the Baotou private function MakeHead ($ opcode, $ param) {return pack ("SSII", "SD", $ this-> TellPut (), $ opcode, $ param );} // simulate the function to overload the private function _ call ($ name, $ arg) {return call_user_func_array (arr Ay ($ this, $ name), $ arg );} /*********************** Uitl *************** * ********** // Convert the hex op to the static function MakeOpcode ($ MAJOR_OP, $ MINOR_OP) {return ($ MAJOR_OP & 0 xffff) <16) | ($ MINOR_OP & 0 xffff ));}} /*** the package class * contains operations on the package body */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 ($ thi S-> 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 ;}}?>

Format

Struct header {int type; // message type int length; // message length} struct MSG_Q2R2DB_PAYRESULT {int serialno; int openid; char payitem [512]; int billno; int zoneid; int providetype; int coins;} indicates the method called. In addition, two php files are required: one is the byte encoding class and the other is the socket encapsulation class. In fact, the main part is the byte encoding class!

Call test

Public function index () {$ socketAddr = "127.0.0.1"; $ socketPort = "10000"; try {$ selfPath = dirname (_ FILE _); require ($ selfPath. "/.. /Tool/Bytes. php "); $ bytes = new Bytes (); $ payitem =" sdfasdfasdfsdfsdfsdfsdfsdf "; $ serialno = 1; $ zoneid = 22; $ openid =" bytes "; $ 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 ); // connect to the server $ sockResult = $ socket-> sendRequest ($ packet); // send the packet to the server sleep (3); $ socket-> disconnect (); // Close link} catch (Exception $ e) {var_dump ($ e); $ this-> log_error ("pay order send to server ". $ e-> getMessage ());}}

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.