AsyncTcpConnection.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. * AsyncTcpConnection.
  20. */
  21. class AsyncTcpConnection extends TcpConnection
  22. {
  23. /**
  24. * Emitted when socket connection is successfully established.
  25. *
  26. * @var callback
  27. */
  28. public $onConnect = null;
  29. /**
  30. * Transport layer protocol.
  31. *
  32. * @var string
  33. */
  34. public $transport = 'tcp';
  35. /**
  36. * Status.
  37. *
  38. * @var int
  39. */
  40. protected $_status = self::STATUS_INITIAL;
  41. /**
  42. * Remote host.
  43. *
  44. * @var string
  45. */
  46. protected $_remoteHost = '';
  47. /**
  48. * Connect start time.
  49. *
  50. * @var string
  51. */
  52. protected $_connectStartTime = 0;
  53. /**
  54. * PHP built-in protocols.
  55. *
  56. * @var array
  57. */
  58. protected static $_builtinTransports = array(
  59. 'tcp' => 'tcp',
  60. 'udp' => 'udp',
  61. 'unix' => 'unix',
  62. 'ssl' => 'ssl',
  63. 'sslv2' => 'sslv2',
  64. 'sslv3' => 'sslv3',
  65. 'tls' => 'tls'
  66. );
  67. /**
  68. * Construct.
  69. *
  70. * @param string $remote_address
  71. * @throws Exception
  72. */
  73. public function __construct($remote_address)
  74. {
  75. // Get the application layer communication protocol and listening address.
  76. list($scheme, $address) = explode(':', $remote_address, 2);
  77. // Check application layer protocol class.
  78. if (!isset(self::$_builtinTransports[$scheme])) {
  79. $scheme = ucfirst($scheme);
  80. $this->protocol = '\\Protocols\\' . $scheme;
  81. if (!class_exists($this->protocol)) {
  82. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  83. if (!class_exists($this->protocol)) {
  84. throw new Exception("class \\Protocols\\$scheme not exist");
  85. }
  86. }
  87. } else {
  88. $this->transport = self::$_builtinTransports[$scheme];
  89. }
  90. $this->_remoteAddress = substr($address, 2);
  91. $this->_remoteHost = substr($this->_remoteAddress, 0, strrpos($this->_remoteAddress, ':'));
  92. $this->id = self::$_idRecorder++;
  93. // For statistics.
  94. self::$statistics['connection_count']++;
  95. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  96. }
  97. /**
  98. * Do connect.
  99. *
  100. * @return void
  101. */
  102. public function connect()
  103. {
  104. if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING && $this->_status !== self::STATUS_CLOSED) {
  105. return;
  106. }
  107. $this->_status = self::STATUS_CONNECTING;
  108. $this->_connectStartTime = microtime(true);
  109. // Open socket connection asynchronously.
  110. $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
  111. STREAM_CLIENT_ASYNC_CONNECT);
  112. // If failed attempt to emit onError callback.
  113. if (!$this->_socket) {
  114. $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
  115. if ($this->_status === self::STATUS_CLOSING) {
  116. $this->destroy();
  117. }
  118. if ($this->_status === self::STATUS_CLOSED) {
  119. $this->onConnect = null;
  120. }
  121. return;
  122. }
  123. // Add socket to global event loop waiting connection is successfully established or faild.
  124. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
  125. }
  126. /**
  127. * Get remote address.
  128. *
  129. * @return string
  130. */
  131. public function getRemoteHost()
  132. {
  133. return $this->_remoteHost;
  134. }
  135. /**
  136. * Try to emit onError callback.
  137. *
  138. * @param int $code
  139. * @param string $msg
  140. * @return void
  141. */
  142. protected function emitError($code, $msg)
  143. {
  144. $this->_status = self::STATUS_CLOSING;
  145. if ($this->onError) {
  146. try {
  147. call_user_func($this->onError, $this, $code, $msg);
  148. } catch (\Exception $e) {
  149. Worker::log($e);
  150. exit(250);
  151. } catch (\Error $e) {
  152. Worker::log($e);
  153. exit(250);
  154. }
  155. }
  156. }
  157. /**
  158. * Check connection is successfully established or faild.
  159. *
  160. * @param resource $socket
  161. * @return void
  162. */
  163. public function checkConnection($socket)
  164. {
  165. // Check socket state.
  166. if ($address = stream_socket_get_name($socket, true)) {
  167. // Remove write listener.
  168. Worker::$globalEvent->del($socket, EventInterface::EV_WRITE);
  169. // Nonblocking.
  170. stream_set_blocking($socket, 0);
  171. stream_set_read_buffer($socket, 0);
  172. // Try to open keepalive for tcp and disable Nagle algorithm.
  173. if (function_exists('socket_import_stream') && $this->transport === 'tcp') {
  174. $raw_socket = socket_import_stream($socket);
  175. socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  176. socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1);
  177. }
  178. // Register a listener waiting read event.
  179. Worker::$globalEvent->add($socket, EventInterface::EV_READ, array($this, 'baseRead'));
  180. // There are some data waiting to send.
  181. if ($this->_sendBuffer) {
  182. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  183. }
  184. $this->_status = self::STATUS_ESTABLISH;
  185. $this->_remoteAddress = $address;
  186. // Try to emit onConnect callback.
  187. if ($this->onConnect) {
  188. try {
  189. call_user_func($this->onConnect, $this);
  190. } catch (\Exception $e) {
  191. Worker::log($e);
  192. exit(250);
  193. } catch (\Error $e) {
  194. Worker::log($e);
  195. exit(250);
  196. }
  197. }
  198. // Try to emit protocol::onConnect
  199. if (method_exists($this->protocol, 'onConnect')) {
  200. try {
  201. call_user_func(array($this->protocol, 'onConnect'), $this);
  202. } catch (\Exception $e) {
  203. Worker::log($e);
  204. exit(250);
  205. } catch (\Error $e) {
  206. Worker::log($e);
  207. exit(250);
  208. }
  209. }
  210. } else {
  211. // Connection failed.
  212. $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(microtime(true) - $this->_connectStartTime, 4) . ' seconds');
  213. if ($this->_status === self::STATUS_CLOSING) {
  214. $this->destroy();
  215. }
  216. if ($this->_status === self::STATUS_CLOSED) {
  217. $this->onConnect = null;
  218. }
  219. }
  220. }
  221. }