AsyncTcpConnection.php 5.9 KB

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