Frame.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Protocols;
  15. use Workerman\Connection\TcpConnection;
  16. /**
  17. * Frame Protocol.
  18. */
  19. class Frame
  20. {
  21. /**
  22. * Check the integrity of the package.
  23. *
  24. * @param string $buffer
  25. * @param TcpConnection $connection
  26. * @return int
  27. */
  28. public static function input($buffer, TcpConnection $connection)
  29. {
  30. if (strlen($buffer) < 4) {
  31. return 0;
  32. }
  33. $unpack_data = unpack('Ntotal_length', $buffer);
  34. return $unpack_data['total_length'];
  35. }
  36. /**
  37. * Decode.
  38. *
  39. * @param string $buffer
  40. * @return string
  41. */
  42. public static function decode($buffer)
  43. {
  44. return substr($buffer, 4);
  45. }
  46. /**
  47. * Encode.
  48. *
  49. * @param string $buffer
  50. * @return string
  51. */
  52. public static function encode($buffer)
  53. {
  54. $total_length = 4 + strlen($buffer);
  55. return pack('N', $total_length) . $buffer;
  56. }
  57. }