Text.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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协议
  18. * 以换行为请求结束标记
  19. * @author walkor <walkor@workerman.net>
  20. */
  21. class Text
  22. {
  23. /**
  24. * 检查包的完整性
  25. * 如果能够得到包长,则返回包的长度,否则返回0继续等待数据
  26. * @param string $buffer
  27. */
  28. public static function input($buffer ,TcpConnection $connection)
  29. {
  30. // 由于没有包头,无法预先知道包长,不能无限制的接收数据,
  31. // 所以需要判断当前接收的数据是否超过限定值
  32. if(strlen($buffer)>=TcpConnection::$maxPackageSize)
  33. {
  34. $connection->close();
  35. return 0;
  36. }
  37. // 获得换行字符"\n"位置
  38. $pos = strpos($buffer, "\n");
  39. // 没有换行符,无法得知包长,返回0继续等待数据
  40. if($pos === false)
  41. {
  42. return 0;
  43. }
  44. // 有换行符,返回当前包长,包含换行符
  45. return $pos+1;
  46. }
  47. /**
  48. * 打包,当向客户端发送数据的时候会自动调用
  49. * @param string $buffer
  50. * @return string
  51. */
  52. public static function encode($buffer)
  53. {
  54. // 加上换行
  55. return $buffer."\n";
  56. }
  57. /**
  58. * 解包,当接收到的数据字节数等于input返回的值(大于0的值)自动调用
  59. * 并传递给onMessage回调函数的$data参数
  60. * @param string $buffer
  61. * @return string
  62. */
  63. public static function decode($buffer)
  64. {
  65. // 去掉换行
  66. return trim($buffer);
  67. }
  68. }