AsyncTcpConnection.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. * Remote URI.
  55. *
  56. * @var string
  57. */
  58. protected $_remoteURI = '';
  59. /**
  60. * PHP built-in protocols.
  61. *
  62. * @var array
  63. */
  64. protected static $_builtinTransports = array(
  65. 'tcp' => 'tcp',
  66. 'udp' => 'udp',
  67. 'unix' => 'unix',
  68. 'ssl' => 'ssl',
  69. 'sslv2' => 'sslv2',
  70. 'sslv3' => 'sslv3',
  71. 'tls' => 'tls'
  72. );
  73. /**
  74. * Construct.
  75. *
  76. * @param string $remote_address
  77. * @throws Exception
  78. */
  79. public function __construct($remote_address)
  80. {
  81. $address_info = parse_url($remote_address);
  82. if (!$address_info) {
  83. echo new \Exception('bad remote_address');
  84. $this->_remoteAddress = $remote_address;
  85. } else {
  86. if (!isset($address_info['port'])) {
  87. $address_info['port'] = 80;
  88. }
  89. if (!isset($address_info['path'])) {
  90. $address_info['path'] = '/';
  91. }
  92. if (!isset($address_info['query'])) {
  93. $address_info['query'] = '';
  94. } else {
  95. $address_info['query'] = '?' . $address_info['query'];
  96. }
  97. $this->_remoteAddress = "{$address_info['host']}:{$address_info['port']}";
  98. $this->_remoteHost = $address_info['host'];
  99. $this->_remoteURI = "{$address_info['path']}{$address_info['query']}";
  100. $scheme = isset($address_info['scheme']) ? $address_info['scheme'] : 'tcp';
  101. }
  102. $this->id = self::$_idRecorder++;
  103. // Check application layer protocol class.
  104. if (!isset(self::$_builtinTransports[$scheme])) {
  105. $scheme = ucfirst($scheme);
  106. $this->protocol = '\\Protocols\\' . $scheme;
  107. if (!class_exists($this->protocol)) {
  108. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  109. if (!class_exists($this->protocol)) {
  110. throw new Exception("class \\Protocols\\$scheme not exist");
  111. }
  112. }
  113. } else {
  114. $this->transport = self::$_builtinTransports[$scheme];
  115. }
  116. // For statistics.
  117. self::$statistics['connection_count']++;
  118. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  119. }
  120. /**
  121. * Do connect.
  122. *
  123. * @return void
  124. */
  125. public function connect()
  126. {
  127. if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING && $this->_status !== self::STATUS_CLOSED) {
  128. return;
  129. }
  130. $this->_status = self::STATUS_CONNECTING;
  131. $this->_connectStartTime = microtime(true);
  132. // Open socket connection asynchronously.
  133. $this->_socket = stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
  134. STREAM_CLIENT_ASYNC_CONNECT);
  135. // If failed attempt to emit onError callback.
  136. if (!$this->_socket) {
  137. $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
  138. if ($this->_status === self::STATUS_CLOSING) {
  139. $this->destroy();
  140. }
  141. if ($this->_status === self::STATUS_CLOSED) {
  142. $this->onConnect = null;
  143. }
  144. return;
  145. }
  146. // Add socket to global event loop waiting connection is successfully established or faild.
  147. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
  148. }
  149. /**
  150. * Get remote address.
  151. *
  152. * @return string
  153. */
  154. public function getRemoteHost()
  155. {
  156. return $this->_remoteHost;
  157. }
  158. /**
  159. * Get remote URI.
  160. *
  161. * @return string
  162. */
  163. public function getRemoteURI()
  164. {
  165. return $this->_remoteURI;
  166. }
  167. /**
  168. * Try to emit onError callback.
  169. *
  170. * @param int $code
  171. * @param string $msg
  172. * @return void
  173. */
  174. protected function emitError($code, $msg)
  175. {
  176. $this->_status = self::STATUS_CLOSING;
  177. if ($this->onError) {
  178. try {
  179. call_user_func($this->onError, $this, $code, $msg);
  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. }
  189. /**
  190. * Check connection is successfully established or faild.
  191. *
  192. * @param resource $socket
  193. * @return void
  194. */
  195. public function checkConnection($socket)
  196. {
  197. // Check socket state.
  198. if ($address = stream_socket_get_name($socket, true)) {
  199. // Remove write listener.
  200. Worker::$globalEvent->del($socket, EventInterface::EV_WRITE);
  201. // Nonblocking.
  202. stream_set_blocking($socket, 0);
  203. stream_set_read_buffer($socket, 0);
  204. // Try to open keepalive for tcp and disable Nagle algorithm.
  205. if (function_exists('socket_import_stream') && $this->transport === 'tcp') {
  206. $raw_socket = socket_import_stream($socket);
  207. socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  208. socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1);
  209. }
  210. // Register a listener waiting read event.
  211. Worker::$globalEvent->add($socket, EventInterface::EV_READ, array($this, 'baseRead'));
  212. // There are some data waiting to send.
  213. if ($this->_sendBuffer) {
  214. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  215. }
  216. $this->_status = self::STATUS_ESTABLISH;
  217. $this->_remoteAddress = $address;
  218. // Try to emit onConnect callback.
  219. if ($this->onConnect) {
  220. try {
  221. call_user_func($this->onConnect, $this);
  222. } catch (\Exception $e) {
  223. Worker::log($e);
  224. exit(250);
  225. } catch (\Error $e) {
  226. Worker::log($e);
  227. exit(250);
  228. }
  229. }
  230. // Try to emit protocol::onConnect
  231. if (method_exists($this->protocol, 'onConnect')) {
  232. try {
  233. call_user_func(array($this->protocol, 'onConnect'), $this);
  234. } catch (\Exception $e) {
  235. Worker::log($e);
  236. exit(250);
  237. } catch (\Error $e) {
  238. Worker::log($e);
  239. exit(250);
  240. }
  241. }
  242. } else {
  243. // Connection failed.
  244. $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(microtime(true) - $this->_connectStartTime, 4) . ' seconds');
  245. if ($this->_status === self::STATUS_CLOSING) {
  246. $this->destroy();
  247. }
  248. if ($this->_status === self::STATUS_CLOSED) {
  249. $this->onConnect = null;
  250. }
  251. }
  252. }
  253. }