UdpConnection.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. * udp连接类(udp实际上是无连接的,这里是为了保持与TCP接口一致)
  17. */
  18. class UdpConnection extends ConnectionInterface
  19. {
  20. /**
  21. * 应用层协议
  22. * 值类似于 Workerman\\Protocols\\Http
  23. * @var string
  24. */
  25. public $protocol = '';
  26. /**
  27. * udp socket 资源
  28. * @var resource
  29. */
  30. protected $_socket = null;
  31. /**
  32. * 对端 ip
  33. * @var string
  34. */
  35. protected $_remoteIp = '';
  36. /**
  37. * 对端 端口
  38. * @var int
  39. */
  40. protected $_remotePort = 0;
  41. /**
  42. * 对端 地址
  43. * 值类似于 192.168.10.100:3698
  44. * @var string
  45. */
  46. protected $_remoteAddress = '';
  47. /**
  48. * 构造函数
  49. * @param resource $socket
  50. * @param string $remote_address
  51. */
  52. public function __construct($socket, $remote_address)
  53. {
  54. $this->_socket = $socket;
  55. $this->_remoteAddress = $remote_address;
  56. }
  57. /**
  58. * 发送数据给对端
  59. * @param string $send_buffer
  60. * @return void|boolean
  61. */
  62. public function send($send_buffer)
  63. {
  64. return strlen($send_buffer) === stream_socket_sendto($this->_socket, $send_buffer, 0, $this->_remoteAddress);
  65. }
  66. /**
  67. * 获得对端 ip
  68. * @return string
  69. */
  70. public function getRemoteIp()
  71. {
  72. if(!$this->_remoteIp)
  73. {
  74. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  75. }
  76. return $this->_remoteIp;
  77. }
  78. /**
  79. * 获得对端端口
  80. */
  81. public function getRemotePort()
  82. {
  83. if(!$this->_remotePort)
  84. {
  85. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  86. }
  87. return $this->_remotePort;
  88. }
  89. /**
  90. * 关闭连接(此处为了保持与TCP接口一致,提供了close方法)
  91. * @void
  92. */
  93. public function close($data = null)
  94. {
  95. if($data !== null)
  96. {
  97. $this->send($data);
  98. }
  99. return true;
  100. }
  101. }