Text.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. * Text Protocol.
  18. */
  19. class Text
  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. // Judge whether the package length exceeds the limit.
  31. if (strlen($buffer) >= TcpConnection::$maxPackageSize) {
  32. $connection->close();
  33. return 0;
  34. }
  35. // Find the position of "\n".
  36. $pos = strpos($buffer, "\n");
  37. // No "\n", packet length is unknown, continue to wait for the data so return 0.
  38. if ($pos === false) {
  39. return 0;
  40. }
  41. // Return the current package length.
  42. return $pos + 1;
  43. }
  44. /**
  45. * Encode.
  46. *
  47. * @param string $buffer
  48. * @return string
  49. */
  50. public static function encode($buffer)
  51. {
  52. // Add "\n"
  53. return $buffer . "\n";
  54. }
  55. /**
  56. * Decode.
  57. *
  58. * @param string $buffer
  59. * @return string
  60. */
  61. public static function decode($buffer)
  62. {
  63. // Remove "\n"
  64. return trim($buffer);
  65. }
  66. }