UdpConnection.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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\Connection;
  15. /**
  16. * UdpConnection.
  17. */
  18. class UdpConnection extends ConnectionInterface
  19. {
  20. /**
  21. * Application layer protocol.
  22. * The format is like this Workerman\\Protocols\\Http.
  23. *
  24. * @var \Workerman\Protocols\ProtocolInterface
  25. */
  26. public $protocol = null;
  27. /**
  28. * Udp socket.
  29. *
  30. * @var resource
  31. */
  32. protected $_socket = null;
  33. /**
  34. * Remote address.
  35. *
  36. * @var string
  37. */
  38. protected $_remoteAddress = '';
  39. /**
  40. * Construct.
  41. *
  42. * @param resource $socket
  43. * @param string $remote_address
  44. */
  45. public function __construct($socket, $remote_address)
  46. {
  47. $this->_socket = $socket;
  48. $this->_remoteAddress = $remote_address;
  49. }
  50. /**
  51. * Sends data on the connection.
  52. *
  53. * @param string $send_buffer
  54. * @param bool $raw
  55. * @return void|boolean
  56. */
  57. public function send($send_buffer, $raw = false)
  58. {
  59. if (false === $raw && $this->protocol) {
  60. $parser = $this->protocol;
  61. $send_buffer = $parser::encode($send_buffer, $this);
  62. if ($send_buffer === '') {
  63. return null;
  64. }
  65. }
  66. return strlen($send_buffer) === stream_socket_sendto($this->_socket, $send_buffer, 0, $this->_remoteAddress);
  67. }
  68. /**
  69. * Get remote IP.
  70. *
  71. * @return string
  72. */
  73. public function getRemoteIp()
  74. {
  75. $pos = strrpos($this->_remoteAddress, ':');
  76. if ($pos) {
  77. return trim(substr($this->_remoteAddress, 0, $pos), '[]');
  78. }
  79. return '';
  80. }
  81. /**
  82. * Get remote port.
  83. *
  84. * @return int
  85. */
  86. public function getRemotePort()
  87. {
  88. if ($this->_remoteAddress) {
  89. return (int)substr(strrchr($this->_remoteAddress, ':'), 1);
  90. }
  91. return 0;
  92. }
  93. /**
  94. * Close connection.
  95. *
  96. * @param mixed $data
  97. * @param bool $raw
  98. * @return bool
  99. */
  100. public function close($data = null, $raw = false)
  101. {
  102. if ($data !== null) {
  103. $this->send($data, $raw);
  104. }
  105. return true;
  106. }
  107. }