UdpConnection.php 2.6 KB

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