JsonProtocol.php 1.3 KB

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