AsyncUdpConnection.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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\EventInterface;
  16. use Workerman\Worker;
  17. use \Exception;
  18. /**
  19. * AsyncUdpConnection.
  20. */
  21. class AsyncUdpConnection extends UdpConnection
  22. {
  23. /**
  24. * Emitted when socket connection is successfully established.
  25. *
  26. * @var callable
  27. */
  28. public $onConnect = null;
  29. /**
  30. * Emitted when socket connection closed.
  31. *
  32. * @var callable
  33. */
  34. public $onClose = null;
  35. /**
  36. * Connected or not.
  37. *
  38. * @var bool
  39. */
  40. protected $connected = false;
  41. /**
  42. * Context option.
  43. *
  44. * @var array
  45. */
  46. protected $_contextOption = null;
  47. /**
  48. * Construct.
  49. *
  50. * @param string $remote_address
  51. * @throws Exception
  52. */
  53. public function __construct($remote_address, $context_option = null)
  54. {
  55. // Get the application layer communication protocol and listening address.
  56. list($scheme, $address) = \explode(':', $remote_address, 2);
  57. // Check application layer protocol class.
  58. if ($scheme !== 'udp') {
  59. $scheme = \ucfirst($scheme);
  60. $this->protocol = '\\Protocols\\' . $scheme;
  61. if (!\class_exists($this->protocol)) {
  62. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  63. if (!\class_exists($this->protocol)) {
  64. throw new Exception("class \\Protocols\\$scheme not exist");
  65. }
  66. }
  67. }
  68. $this->_remoteAddress = \substr($address, 2);
  69. $this->_contextOption = $context_option;
  70. }
  71. /**
  72. * For udp package.
  73. *
  74. * @param resource $socket
  75. * @return bool
  76. */
  77. public function baseRead($socket)
  78. {
  79. $recv_buffer = \stream_socket_recvfrom($socket, Worker::MAX_UDP_PACKAGE_SIZE, 0, $remote_address);
  80. if (false === $recv_buffer || empty($remote_address)) {
  81. return false;
  82. }
  83. if ($this->onMessage) {
  84. if ($this->protocol) {
  85. $parser = $this->protocol;
  86. $recv_buffer = $parser::decode($recv_buffer, $this);
  87. }
  88. ++ConnectionInterface::$statistics['total_request'];
  89. try {
  90. \call_user_func($this->onMessage, $this, $recv_buffer);
  91. } catch (\Exception $e) {
  92. Worker::stopAll(250, $e);
  93. } catch (\Error $e) {
  94. Worker::stopAll(250, $e);
  95. }
  96. }
  97. return true;
  98. }
  99. /**
  100. * Sends data on the connection.
  101. *
  102. * @param string $send_buffer
  103. * @param bool $raw
  104. * @return void|boolean
  105. */
  106. public function send($send_buffer, $raw = false)
  107. {
  108. if (false === $raw && $this->protocol) {
  109. $parser = $this->protocol;
  110. $send_buffer = $parser::encode($send_buffer, $this);
  111. if ($send_buffer === '') {
  112. return;
  113. }
  114. }
  115. if ($this->connected === false) {
  116. $this->connect();
  117. }
  118. return \strlen($send_buffer) === \stream_socket_sendto($this->_socket, $send_buffer, 0);
  119. }
  120. /**
  121. * Close connection.
  122. *
  123. * @param mixed $data
  124. * @param bool $raw
  125. *
  126. * @return bool
  127. */
  128. public function close($data = null, $raw = false)
  129. {
  130. if ($data !== null) {
  131. $this->send($data, $raw);
  132. }
  133. Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
  134. \fclose($this->_socket);
  135. $this->connected = false;
  136. // Try to emit onClose callback.
  137. if ($this->onClose) {
  138. try {
  139. \call_user_func($this->onClose, $this);
  140. } catch (\Exception $e) {
  141. Worker::stopAll(250, $e);
  142. } catch (\Error $e) {
  143. Worker::stopAll(250, $e);
  144. }
  145. }
  146. $this->onConnect = $this->onMessage = $this->onClose = null;
  147. return true;
  148. }
  149. /**
  150. * Connect.
  151. *
  152. * @return void
  153. */
  154. public function connect()
  155. {
  156. if ($this->connected === true) {
  157. return;
  158. }
  159. if ($this->_contextOption) {
  160. $context = \stream_context_create($this->_contextOption);
  161. $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg,
  162. 30, \STREAM_CLIENT_CONNECT, $context);
  163. } else {
  164. $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg);
  165. }
  166. if (!$this->_socket) {
  167. Worker::safeEcho(new \Exception($errmsg));
  168. return;
  169. }
  170. \stream_set_blocking($this->_socket, false);
  171. if ($this->onMessage) {
  172. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  173. }
  174. $this->connected = true;
  175. // Try to emit onConnect callback.
  176. if ($this->onConnect) {
  177. try {
  178. \call_user_func($this->onConnect, $this);
  179. } catch (\Exception $e) {
  180. Worker::stopAll(250, $e);
  181. } catch (\Error $e) {
  182. Worker::stopAll(250, $e);
  183. }
  184. }
  185. }
  186. }