bytes.php  字节编码类

  1. /**
  2. * byte数组与字符串转化类
  3. * @author
  4. * created on 2011-7-15
  5. */
  6.  
  7. class bytes {
  8.  
  9. /**
  10. * 转换一个string字符串为byte数组
  11. * @param $str 须要转换的字符串
  12. * @param $bytes 目标byte数组
  13. * @author zikie
  14. */
  15.  
  16. public static function getbytes($str) {
  17.  
  18. $len = strlen($str);
  19. $bytes = array();
  20. for($i=0;$i<$len;$i++) {
  21. if(ord($str[$i]) >= 128){
  22. $byte = ord($str[$i]) - 256;
  23. }else{
  24. $byte = ord($str[$i]);
  25. }
  26. $bytes[] = $byte ;
  27. }
  28. return $bytes;
  29. }
  30.  
  31. /**
  32. * 将字节数组转化为string类型的数据
  33. * @param $bytes 字节数组
  34. * @param $str 目标字符串
  35. * @return 一个string类型的数据
  36. */
  37.  
  38. public static function tostr($bytes) {
  39. $str = '';
  40. foreach($bytes as $ch) {
  41. $str .= chr($ch);
  42. }
  43.  
  44. return $str;
  45. }
  46.  
  47. /**
  48. * 转换一个int为byte数组
  49. * @param $byt 目标byte数组
  50. * @param $val 须要转换的字符串
  51. * @author zikie
  52. */
  53.  
  54. public static function integertobytes($val) {
  55. $byt = array();
  56. $byt[0] = ($val & 0xff);
  57. $byt[1] = ($val >> 8 & 0xff);
  58. $byt[2] = ($val >> 16 & 0xff);
  59. $byt[3] = ($val >> 24 & 0xff);
  60. return $byt;
  61. }
  62.  
  63. /**
  64. * 从字节数组中指定的位置读取一个integer类型的数据
  65. * @param $bytes 字节数组
  66. * @param $position 指定的開始位置
  67. * @return 一个integer类型的数据
  68. */
  69.  
  70. public static function bytestointeger($bytes, $position) {
  71. $val = 0;
  72. $val = $bytes[$position + 3] & 0xff;
  73. $val <<= 8;
  74. $val |= $bytes[$position + 2] & 0xff;
  75. $val <<= 8;
  76. $val |= $bytes[$position + 1] & 0xff;
  77. $val <<= 8;
  78. $val |= $bytes[$position] & 0xff;
  79. return $val;
  80. }
  81.  
  82. /**
  83. * 转换一个shor字符串为byte数组
  84. * @param $byt 目标byte数组
  85. * @param $val 须要转换的字符串
  86. * @author zikie
  87. */
  88.  
  89. public static function shorttobytes($val) {
  90. $byt = array();
  91. $byt[0] = ($val & 0xff);
  92. $byt[1] = ($val >> 8 & 0xff);
  93. return $byt;
  94. }
  95.  
  96. /**
  97. * 从字节数组中指定的位置读取一个short类型的数据。
  98.  
  99. * @param $bytes 字节数组
  100. * @param $position 指定的開始位置
  101. * @return 一个short类型的数据
  102. */
  103.  
  104. public static function bytestoshort($bytes, $position) {
  105. $val = 0;
  106. $val = $bytes[$position + 1] & 0xff;
  107. $val = $val << 8;
  108. $val |= $bytes[$position] & 0xff;
  109. return $val;
  110. }
  111.  
  112. }

socket.class.php  socket赋值类

  1. <?php
  2. define("CONNECTED", true);
  3. define("DISCONNECTED", false);
  4.  
  5. /**
  6. * Socket class
  7. *
  8. *
  9. * @author Seven
  10. */
  11. Class Socket
  12. {
  13. private static $instance;
  14.  
  15. private $connection = null;
  16.  
  17. private $connectionState = DISCONNECTED;
  18.  
  19. private $defaultHost = "127.0.0.1";
  20.  
  21. private $defaultPort = 80;
  22.  
  23. private $defaultTimeout = 10;
  24.  
  25. public $debug = false;
  26.  
  27. function __construct()
  28. {
  29.  
  30. }
  31. /**
  32. * Singleton pattern. Returns the same instance to all callers
  33. *
  34. * @return Socket
  35. */
  36. public static function singleton()
  37. {
  38. if (self::$instance == null || ! self::$instance instanceof Socket)
  39. {
  40. self::$instance = new Socket();
  41.  
  42. }
  43. return self::$instance;
  44. }
  45. /**
  46. * Connects to the socket with the given address and port
  47. *
  48. * @return void
  49. */
  50. public function connect($serverHost=false, $serverPort=false, $timeOut=false)
  51. {
  52. if($serverHost == false)
  53. {
  54. $serverHost = $this->defaultHost;
  55. }
  56.  
  57. if($serverPort == false)
  58. {
  59. $serverPort = $this->defaultPort;
  60. }
  61. $this->defaultHost = $serverHost;
  62. $this->defaultPort = $serverPort;
  63.  
  64. if($timeOut == false)
  65. {
  66. $timeOut = $this->defaultTimeout;
  67. }
  68. $this->connection = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
  69.  
  70. if(socket_connect($this->connection,$serverHost,$serverPort) == false)
  71. {
  72. $errorString = socket_strerror(socket_last_error($this->connection));
  73. $this->_throwError("Connecting to {$serverHost}:{$serverPort} failed.<br>Reason: {$errorString}");
  74. }else{
  75. $this->_throwMsg("Socket connected!");
  76. }
  77.  
  78. $this->connectionState = CONNECTED;
  79. }
  80.  
  81. /**
  82. * Disconnects from the server
  83. *
  84. * @return True on succes, false if the connection was already closed
  85. */
  86. public function disconnect()
  87. {
  88. if($this->validateConnection())
  89. {
  90. socket_close($this->connection);
  91. $this->connectionState = DISCONNECTED;
  92. $this->_throwMsg("Socket disconnected!");
  93. return true;
  94. }
  95. return false;
  96. }
  97. /**
  98. * Sends a command to the server
  99. *
  100. * @return string Server response
  101. */
  102. public function sendRequest($command)
  103. {
  104. if($this->validateConnection())
  105. {
  106. $result = socket_write($this->connection,$command,strlen($command));
  107. return $result;
  108. }
  109. $this->_throwError("Sending command \"{$command}\" failed.<br>Reason: Not connected");
  110. }
  111.  
  112. public function isConn()
  113. {
  114. return $this->connectionState;
  115. }
  116.  
  117. public function getUnreadBytes()
  118. {
  119.  
  120. $info = socket_get_status($this->connection);
  121. return $info['unread_bytes'];
  122.  
  123. }
  124.  
  125. public function getConnName(&$addr, &$port)
  126. {
  127. if ($this->validateConnection())
  128. {
  129. socket_getsockname($this->connection,$addr,$port);
  130. }
  131. }
  132.  
  133. /**
  134. * Gets the server response (not multilined)
  135. *
  136. * @return string Server response
  137. */
  138. public function getResponse()
  139. {
  140. $read_set = array($this->connection);
  141.  
  142. while (($events = socket_select($read_set, $write_set = NULL, $exception_set = NULL, 0)) !== false)
  143. {
  144. if ($events > 0)
  145. {
  146. foreach ($read_set as $so)
  147. {
  148. if (!is_resource($so))
  149. {
  150. $this->_throwError("Receiving response from server failed.<br>Reason: Not connected");
  151. return false;
  152. }elseif ( ( $ret = @socket_read($so,4096,PHP_BINARY_READ) ) == false){
  153. $this->_throwError("Receiving response from server failed.<br>Reason: Not bytes to read");
  154. return false;
  155. }
  156. return $ret;
  157. }
  158. }
  159. }
  160.  
  161. return false;
  162. }
  163. public function waitForResponse()
  164. {
  165. if($this->validateConnection())
  166. {
  167. return socket_read($this->connection, 2048);
  168. }
  169.  
  170. $this->_throwError("Receiving response from server failed.<br>Reason: Not connected");
  171. return false;
  172. }
  173. /**
  174. * Validates the connection state
  175. *
  176. * @return bool
  177. */
  178. private function validateConnection()
  179. {
  180. return (is_resource($this->connection) && ($this->connectionState != DISCONNECTED));
  181. }
  182. /**
  183. * Throws an error
  184. *
  185. * @return void
  186. */
  187. private function _throwError($errorMessage)
  188. {
  189. echo "Socket error: " . $errorMessage;
  190. }
  191. /**
  192. * Throws an message
  193. *
  194. * @return void
  195. */
  196. private function _throwMsg($msg)
  197. {
  198. if ($this->debug)
  199. {
  200. echo "Socket message: " . $msg . "\n\n";
  201. }
  202. }
  203. /**
  204. * If there still was a connection alive, disconnect it
  205. */
  206. public function __destruct()
  207. {
  208. $this->disconnect();
  209. }
  210. }
  211.  
  212. ?>

PacketBase.class.php  打包类

  1. <?
  2.  
  3. php
  4. /**
  5. * PacketBase class
  6. *
  7. * 用以处理与c++服务端交互的sockets 包
  8. *
  9. * 注意:不支持宽字符
  10. *
  11. * @author Seven <seven@qoolu.com>
  12. *
  13. */
  14. class PacketBase extends ContentHandler
  15. {
  16. private $head;
  17. private $params;
  18. private $opcode;
  19. /**************************construct***************************/
  20. function __construct()
  21. {
  22. $num = func_num_args();
  23. $args = func_get_args();
  24. switch($num){
  25. case 0:
  26. //do nothing 用来生成对象的
  27. break;
  28. case 1:
  29. $this->__call('__construct1', $args);
  30. break;
  31. case 2:
  32. $this->__call('__construct2', $args);
  33. break;
  34. default:
  35. throw new Exception();
  36. }
  37. }
  38. //无參数
  39. public function __construct1($OPCODE)
  40. {
  41. $this->opcode = $OPCODE;
  42. $this->params = 0;
  43. }
  44. //有參数
  45. public function __construct2($OPCODE, $PARAMS)
  46. {
  47. $this->opcode = $OPCODE;
  48. $this->params = $PARAMS;
  49. }
  50. //析构
  51. function __destruct()
  52. {
  53. unset($this->head);
  54. unset($this->buf);
  55. }
  56.  
  57. //打包
  58. public function pack()
  59. {
  60. $head = $this->MakeHead($this->opcode,$this->params);
  61. return $head.$this->buf;
  62. }
  63. //解包
  64. public function unpack($packet,$noHead = false)
  65. {
  66.  
  67. $this->buf = $packet;
  68. if (!$noHead){
  69. $recvHead = unpack("S2hd/I2pa",$packet);
  70. $SD = $recvHead[hd1];//SD
  71. $this->contentlen = $recvHead[hd2];//content len
  72. $this->opcode = $recvHead[pa1];//opcode
  73. $this->params = $recvHead[pa2];//params
  74.  
  75. $this->pos = 12;//去除包头长度
  76.  
  77. if ($SD != 21316)
  78. {
  79. return false;
  80. }
  81. }else
  82. {
  83. $this->pos = 0;
  84. }
  85. return true;
  86. }
  87. public function GetOP()
  88. {
  89. if ($this->buf)
  90. {
  91. return $this->opcode;
  92. }
  93. return 0;
  94. }
  95. /************************private***************************/
  96. //构造包头
  97. private function MakeHead($opcode,$param)
  98. {
  99. return pack("SSII","SD",$this->TellPut(),$opcode,$param);
  100. }
  101.  
  102. //用以模拟函数重载
  103. private function __call($name, $arg)
  104. {
  105. return call_user_func_array(array($this, $name), $arg);
  106. }
  107.  
  108. /***********************Uitl***************************/
  109. //将16进制的op转成10进制
  110. static function MakeOpcode($MAJOR_OP, $MINOR_OP)
  111. {
  112. return ((($MAJOR_OP & 0xffff) << 16) | ($MINOR_OP & 0xffff));
  113. }
  114. }
  115. /**
  116. * 包体类
  117. * 包括了对包体的操作
  118. */
  119. class ContentHandler
  120. {
  121. public $buf;
  122. public $pos;
  123. public $contentlen;//use for unpack
  124.  
  125. function __construct()
  126. {
  127. $this->buf = "";
  128. $this->contentlen = 0;
  129. $this->pos = 0;
  130. }
  131. function __destruct()
  132. {
  133. unset($this->buf);
  134. }
  135.  
  136. public function PutInt($int)
  137. {
  138. $this->buf .= pack("i",(int)$int);
  139. }
  140. public function PutUTF($str)
  141. {
  142. $l = strlen($str);
  143. $this->buf .= pack("s",$l);
  144. $this->buf .= $str;
  145. }
  146. public function PutStr($str)
  147. {
  148. return $this->PutUTF($str);
  149. }
  150.  
  151. public function TellPut()
  152. {
  153. return strlen($this->buf);
  154. }
  155.  
  156. /*******************************************/
  157.  
  158. public function GetInt()
  159. {
  160. //$cont = substr($out,$l,4);
  161. $get = unpack("@".$this->pos."/i",$this->buf);
  162. if (is_int($get[1])){
  163. $this->pos += 4;
  164. return $get[1];
  165. }
  166. return 0;
  167. }
  168. public function GetShort()
  169. {
  170. $get = unpack("@".$this->pos."/S",$this->buf);
  171. if (is_int($get[1])){
  172. $this->pos += 2;
  173. return $get[1];
  174. }
  175. return 0;
  176. }
  177. public function GetUTF()
  178. {
  179. $getStrLen = $this->GetShort();
  180.  
  181. if ($getStrLen > 0)
  182. {
  183. $end = substr($this->buf,$this->pos,$getStrLen);
  184. $this->pos += $getStrLen;
  185. return $end;
  186. }
  187. return '';
  188. }
  189. /***************************/
  190.  
  191. public function GetBuf()
  192. {
  193. return $this->buf;
  194. }
  195.  
  196. public function SetBuf($strBuf)
  197. {
  198. $this->buf = $strBuf;
  199. }
  200.  
  201. public function ResetBuf(){
  202. $this->buf = "";
  203. $this->contentlen = 0;
  204. $this->pos = 0;
  205. }
  206.  
  207. }
  208.  
  209. ?>

格式

  1. struct header
  2. {
  3. int type; // 消息类型
  4. int length; // 消息长度
  5. }
  6.  
  7. struct MSG_Q2R2DB_PAYRESULT
  8.  
  9. {
  10.  
  11. int serialno;
  12. int openid;
  13. char payitem[512];
  14. int billno;
  15. int zoneid;
  16. int providetype;
  17. int coins;
  18.  
  19. }
  20.  
  21. 调用的方法,另外需require两个php文件。一个是字节编码类,另外一个socket封装类。事实上主要看字节编码类就能够了!

调用測试

  1. public function index() {
  2. $socketAddr = "127.0.0.1";
  3. $socketPort = "10000";
  4. try {
  5.  
  6. $selfPath = dirname ( __FILE__ );
  7. require ($selfPath . "/../Tool/Bytes.php");
  8. $bytes = new Bytes ();
  9.  
  10. $payitem = "sdfasdfasdfsdfsdfsdfsdfsdfsdf";
  11. $serialno = 1;
  12. $zoneid = 22;
  13. $openid = "CFF47C448D4AA2069361567B6F8299C2";
  14.  
  15. $billno = 1;
  16. $providetype = 1;
  17. $coins = 1;
  18.  
  19. $headType = 10001;
  20. $headLength = 56 + intval(strlen($payitem ));
  21.  
  22. $headType = $bytes->integerToBytes ( intval ( $headType ) );
  23. $headLength = $bytes->integerToBytes ( intval ( $headLength ) );
  24. $serialno = $bytes->integerToBytes ( intval ( $serialno ) );
  25. $zoneid = $bytes->integerToBytes ( intval ( $zoneid ) );
  26. $openid = $bytes->getBytes( $openid );
  27. $payitem_len = $bytes->integerToBytes ( intval ( strlen($payitem) ) );
  28. $payitem = $bytes->getBytes($payitem);
  29. $billno = $bytes->integerToBytes ( intval ( $billno ) );
  30. $providetype = $bytes->integerToBytes ( intval ( $providetype ) );
  31. $coins = $bytes->integerToBytes ( intval ( $coins ) );
  32.  
  33. $return_betys = array_merge ($headType , $headLength , $serialno , $zoneid , $openid,$payitem_len ,$payitem,$billno,$providetype,$coins);
  34.  
  35. $msg = $bytes->toStr ($return_betys);
  36. $strLen = strlen($msg);
  37.  
  38. $packet = pack("a{$strLen}", $msg);
  39. $pckLen = strlen($packet);
  40.  
  41. $socket = Socket::singleton ();
  42. $socket->connect ( $socketAddr, $socketPort ); //连server
  43. $sockResult = $socket->sendRequest ( $packet); // 将包发送给server
  44.  
  45. sleep ( 3 );
  46. $socket->disconnect (); //关闭链接
  47.  
  48. } catch ( Exception $e ) {
  49. var_dump($e);
  50. $this->log_error("pay order send to server".$e->getMessage());
  51. }
  52. }

Php socket数据编码的更多相关文章

  1. socket网络编程

    一.客户端/服务器架构 C/S架构,包括 1.硬件C/S架构(打印机) 2.软件C/S架构(Web服务) 最常用的软件服务器就是Web服务器,一台机器里放了一些网页或Web应用程序,然后启动服务,这样 ...

  2. 利用BlazeDS的AMF3数据封装与Flash 进行Socket通讯

    前几天看到了Adobe有个开源项目BlazeDS,里面提供了Java封装AMF3格式的方法.这个项目貌似主要是利用Flex来Remoting的,不过我们可以利用他来与Flash中的Socket通讯. ...

  3. Delphi和JAVA用UTF-8编码进行Socket通信例子

    最近的项目(Delphi开发),需要经常和java语言开发的系统进行数据交互(Socket通信方式),数据编码约定采用UTF-8编码. 令我无语的是:JAVA系统那边反映说,Delphi发的数据他们收 ...

  4. 【PHPsocket编程专题(理论篇)】初步理解TCP/IP、Http、Socket.md

    前言 我们平时说的最多的socket是什么呢,实际上socket是对TCP/IP协议的封装,Socket本身并不是协议,而是一个调用接口(API).那TCP/IP又是什么呢?TCP/IP是ISO/OS ...

  5. .Net remoting, Webservice,WCF,Socket区别

    传统上,我们把计算机后台程序(Daemon)提供的功能,称为"服务"(service).比如,让一个杀毒软件在后台运行,它会自动监控系统,那么这种自动监控就是一个"服务& ...

  6. Socket编程之聊天程序 - 模拟Fins/ModBus协议通信过程

    设备控制软件编程涉及到的基本通信方式主要有TCP/IP与串口,用到的数据通信协议有Fins与ModBus. 更高级别的通信如.net中的Remoting与WCF在进行C/S架构软件开发时会采用. 本篇 ...

  7. socket接收大数据流

    客户端: import socket client = socket.socket() client.connect(("127.0.0.1", 9999)) while True ...

  8. python - 远程主机执行命令练习(socket UDP + subprocess.Popen()) 练习1

    环境是windows 环境. server端: import socket import subprocess ss = socket.socket(socket.AF_INET,socket.SOC ...

  9. C#使用ProtocolBuffer(ProtoBuf)进行Unity中的Socket通信

    首先来说一下本文中例子所要实现的功能: 基于ProtoBuf序列化对象 使用Socket实现时时通信 数据包的编码和解码 下面来看具体的步骤: 一.Unity中使用ProtoBuf 导入DLL到Uni ...

随机推荐

  1. 关于TJOI2014的一道题——Alice and Bob

    B Alice and Bob •输入输出文件: alice.in/alice.out •源文件名: alice.cpp/alice.c/alice.pas • 时间限制: 1s 内存限制: 128M ...

  2. 有关css的选择器优先级以及父子选择器

    css,又称样式重叠表,如今的网页的样式基本是div+css写出来的,功能十分强大,要想在html文件中引入css文件需要在<head></head>标签内输入一行:<l ...

  3. 快速录入快递地址API接口实现

    电商.ERP等行业下单环节极其重要,如何提高下单的效率已经成为首要问题.快速下单对于客户来说,为提前发货争取了时间:对于卖家来说,提高了库存周转率及利用率.快速下单的接口实现,需要解决如下几个问题:1 ...

  4. 前端Canvas思维导图笔记

    看不清的朋友右键保存或者新窗口打开哦!喜欢我可以关注我,还有更多前端思维导图笔记

  5. Leetcode0100--Same Tree 相同树

    [转载请注明]http://www.cnblogs.com/igoslly/p/8707664.html 来看一下题目: Given two binary trees, write a functio ...

  6. js 如何给标签增加属性

    <html> <head> <meta charset="UTF-8"> <title></title> </he ...

  7. T-SQL查询高级--理解SQL SERVER中非聚集索引的覆盖,连接,交叉和过滤

      写在前面:这是第一篇T-SQL查询高级系列文章.但是T-SQL查询进阶系列还远远没有写完.这个主题放到高级我想是因为这个主题需要一些进阶的知识作为基础..如果文章中有错误的地方请不吝指正.本篇文章 ...

  8. hibernate_02_session介绍

    什么是session? hibernate的session对象就相当于jdbc的connection.我们对数据库的操作(增删改等)都是使用的session方法. 写一个java类 package c ...

  9. beetl模板入门例子

    加入maven依赖 <dependency> <groupId>org.beetl</groupId> <artifactId>beetl-core&l ...

  10. ubuntu18.0安装RabbitMQ

    RabbitMQ是一个消息队列,用于实现应用程序的异步和解耦.生产者将生产消息传送到队列,消费中从队列中拿取消息并处理.生产者不用关心是谁来消费,消费者不用关系是谁在生产消息,从而达到解耦的目的.本文 ...