JsonProtocol.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. $recv_length = strlen($buffer);
  15. // 接收到的数据长度不够?
  16. if($recv_length<4)
  17. {
  18. return 4 - $recv_length;
  19. }
  20. // 读取首部4个字节,网络字节序int
  21. $buffer_data = unpack('Ntotal_length', $buffer);
  22. // 得到这次数据的整体长度(字节)
  23. $total_length = $buffer_data['total_length'];
  24. if($total_length>$recv_length)
  25. {
  26. // 还有这么多字节要接收
  27. return $total_length - $recv_length;
  28. }
  29. // 接收完毕
  30. return 0;
  31. }
  32. // 打包
  33. public static function encode($data)
  34. {
  35. // 选用json格式化数据
  36. $buffer = json_encode($data);
  37. // 包的整体长度为json长度加首部四个字节(首部数据包长度存储占用空间)
  38. $total_length = 4 + strlen($buffer);
  39. return pack('N', $total_length) . $buffer;
  40. }
  41. // 解包
  42. public static function decode($buffer)
  43. {
  44. $buffer_data = unpack('Ntotal_length', $buffer);
  45. // 得到这次数据的整体长度(字节)
  46. $total_length = $buffer_data['total_length'];
  47. // json的数据
  48. $json_string = substr($buffer, 4);
  49. return json_decode($json_string, true);
  50. }
  51. }