AsyncTcpConnection.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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_CONNECTING;
  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. $this->_connectStartTime = microtime(true);
  105. // Open socket connection asynchronously.
  106. $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
  107. STREAM_CLIENT_ASYNC_CONNECT);
  108. // If failed attempt to emit onError callback.
  109. if (!$this->_socket) {
  110. $this->_status = self::STATUS_CLOSED;
  111. $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
  112. return;
  113. }
  114. // Add socket to global event loop waiting connection is successfully established or faild.
  115. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
  116. }
  117. /**
  118. * Get remote address.
  119. *
  120. * @return string
  121. */
  122. public function getRemoteHost()
  123. {
  124. return $this->_remoteHost;
  125. }
  126. /**
  127. * Try to emit onError callback.
  128. *
  129. * @param int $code
  130. * @param string $msg
  131. * @return void
  132. */
  133. protected function emitError($code, $msg)
  134. {
  135. if ($this->onError) {
  136. try {
  137. call_user_func($this->onError, $this, $code, $msg);
  138. } catch (\Exception $e) {
  139. Worker::log($e);
  140. exit(250);
  141. } catch (\Error $e) {
  142. Worker::log($e);
  143. exit(250);
  144. }
  145. }
  146. }
  147. /**
  148. * Check connection is successfully established or faild.
  149. *
  150. * @param resource $socket
  151. * @return void
  152. */
  153. public function checkConnection($socket)
  154. {
  155. // Check socket state.
  156. if (stream_socket_get_name($socket, true)) {
  157. // Remove write listener.
  158. Worker::$globalEvent->del($socket, EventInterface::EV_WRITE);
  159. // Nonblocking.
  160. stream_set_blocking($socket, 0);
  161. stream_set_read_buffer($socket, 0);
  162. // Try to open keepalive for tcp and disable Nagle algorithm.
  163. if (function_exists('socket_import_stream') && $this->transport === 'tcp') {
  164. $raw_socket = socket_import_stream($socket);
  165. socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  166. socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1);
  167. }
  168. // Register a listener waiting read event.
  169. Worker::$globalEvent->add($socket, EventInterface::EV_READ, array($this, 'baseRead'));
  170. // There are some data waiting to send.
  171. if ($this->_sendBuffer) {
  172. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  173. }
  174. $this->_status = self::STATUS_ESTABLISH;
  175. $this->_remoteAddress = stream_socket_get_name($socket, true);
  176. // Try to emit onConnect callback.
  177. if ($this->onConnect) {
  178. try {
  179. call_user_func($this->onConnect, $this);
  180. } catch (\Exception $e) {
  181. Worker::log($e);
  182. exit(250);
  183. } catch (\Error $e) {
  184. Worker::log($e);
  185. exit(250);
  186. }
  187. }
  188. } else {
  189. // Connection failed.
  190. $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(microtime(true) - $this->_connectStartTime, 4) . ' seconds');
  191. $this->destroy();
  192. $this->onConnect = null;
  193. }
  194. }
  195. }