UdpConnection.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. * connection
  10. * @author walkor<walkor@workerman.net>
  11. */
  12. class UdpConnection extends ConnectionInterface
  13. {
  14. /**
  15. * protocol
  16. * @var string
  17. */
  18. public $protocol = '';
  19. /**
  20. * the socket
  21. * @var resource
  22. */
  23. protected $_socket = null;
  24. /**
  25. * remote ip
  26. * @var string
  27. */
  28. protected $_remoteIp = '';
  29. /**
  30. * remote port
  31. * @var int
  32. */
  33. protected $_remotePort = 0;
  34. /**
  35. * remote address
  36. * @var string
  37. */
  38. protected $_remoteAddress = '';
  39. /**
  40. * create a connection
  41. * @param resource $socket
  42. * @param string $remote_address
  43. */
  44. public function __construct($socket, $remote_address)
  45. {
  46. $this->_socket = $socket;
  47. $this->_remoteAddress = $remote_address;
  48. }
  49. /**
  50. * send buffer to client
  51. * @param string $send_buffer
  52. * @return void|boolean
  53. */
  54. public function send($send_buffer)
  55. {
  56. return strlen($send_buffer) === stream_socket_sendto($this->_socket, $send_buffer, 0, $this->_remoteAddress);
  57. }
  58. /**
  59. * get remote ip
  60. * @return string
  61. */
  62. public function getRemoteIp()
  63. {
  64. if(!$this->_remoteIp)
  65. {
  66. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  67. }
  68. return $this->_remoteIp;
  69. }
  70. /**
  71. * get remote port
  72. */
  73. public function getRemotePort()
  74. {
  75. if(!$this->_remotePort)
  76. {
  77. list($this->_remoteIp, $this->_remotePort) = explode(':', $this->_remoteAddress, 2);
  78. }
  79. return $this->_remotePort;
  80. }
  81. /**
  82. * close the connection
  83. * @void
  84. */
  85. public function close($data = null)
  86. {
  87. if($data !== null)
  88. {
  89. $this->send($data);
  90. }
  91. return true;
  92. }
  93. }