UdpConnection.php 2.2 KB

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