JsonProtocol.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace Protocols;
  3. /**
  4. * 以四字节int标记请求长度的json协议
  5. * 协议格式int+json
  6. * @author walkor
  7. */
  8. class JsonProtocol
  9. {
  10. // 根据首部四个字节(int)判断数据是否接收完毕
  11. public static function check($buffer)
  12. {
  13. // 读取首部四个字节
  14. $buffer_data = unpack('Ntotal_length', $buffer);
  15. // 得到这次数据的整体长度(字节)
  16. $total_length = $buffer_data['total_length'];
  17. // 已经收到的长度(字节)
  18. $recv_length = strlen($buffer);
  19. if($total_length>$recv_length)
  20. {
  21. // 还有这么多字节要接收
  22. return $total_length - $recv_length;
  23. }
  24. // 接收完毕
  25. return 0;
  26. }
  27. // 打包
  28. public static function encode($data)
  29. {
  30. // 选用json格式化数据
  31. $buffer = json_encode($data);
  32. // 包的整体长度为json长度加首部四个字节(首部数据包长度存储占用空间)
  33. $total_length = 4 + strlen($buffer);
  34. return pack('N', $total_length) . $buffer;
  35. }
  36. // 解包
  37. public static function decode($buffer)
  38. {
  39. $buffer_data = unpack('Ntotal_length', $buffer);
  40. // 得到这次数据的整体长度(字节)
  41. $total_length = $buffer_data['total_length'];
  42. // json的数据
  43. $json_string = substr($buffer, 4);
  44. return json_decode($json_string, true);
  45. }
  46. }