AsyncTcpConnection.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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\Lib\Timer;
  17. use Workerman\Worker;
  18. use \Exception;
  19. /**
  20. * AsyncTcpConnection.
  21. */
  22. class AsyncTcpConnection extends TcpConnection
  23. {
  24. /**
  25. * Emitted when socket connection is successfully established.
  26. *
  27. * @var callable|null
  28. */
  29. public $onConnect = null;
  30. /**
  31. * Transport layer protocol.
  32. *
  33. * @var string
  34. */
  35. public $transport = 'tcp';
  36. /**
  37. * Status.
  38. *
  39. * @var int
  40. */
  41. protected $_status = self::STATUS_INITIAL;
  42. /**
  43. * Remote host.
  44. *
  45. * @var string
  46. */
  47. protected $_remoteHost = '';
  48. /**
  49. * Remote port.
  50. *
  51. * @var int
  52. */
  53. protected $_remotePort = 80;
  54. /**
  55. * Connect start time.
  56. *
  57. * @var float
  58. */
  59. protected $_connectStartTime = 0;
  60. /**
  61. * Remote URI.
  62. *
  63. * @var string
  64. */
  65. protected $_remoteURI = '';
  66. /**
  67. * Context option.
  68. *
  69. * @var array
  70. */
  71. protected $_contextOption = null;
  72. /**
  73. * Reconnect timer.
  74. *
  75. * @var int
  76. */
  77. protected $_reconnectTimer = null;
  78. /**
  79. * PHP built-in protocols.
  80. *
  81. * @var array
  82. */
  83. protected static $_builtinTransports = array(
  84. 'tcp' => 'tcp',
  85. 'udp' => 'udp',
  86. 'unix' => 'unix',
  87. 'ssl' => 'ssl',
  88. 'sslv2' => 'sslv2',
  89. 'sslv3' => 'sslv3',
  90. 'tls' => 'tls'
  91. );
  92. /**
  93. * Construct.
  94. *
  95. * @param string $remote_address
  96. * @param array $context_option
  97. * @throws Exception
  98. */
  99. public function __construct($remote_address, array $context_option = array())
  100. {
  101. $address_info = \parse_url($remote_address);
  102. if (!$address_info) {
  103. list($scheme, $this->_remoteAddress) = \explode(':', $remote_address, 2);
  104. if('unix' === strtolower($scheme)) {
  105. $this->_remoteAddress = substr($remote_address, strpos($remote_address, '/') + 2);
  106. }
  107. if (!$this->_remoteAddress) {
  108. Worker::safeEcho(new \Exception('bad remote_address'));
  109. }
  110. } else {
  111. if (!isset($address_info['port'])) {
  112. $address_info['port'] = 0;
  113. }
  114. if (!isset($address_info['path'])) {
  115. $address_info['path'] = '/';
  116. }
  117. if (!isset($address_info['query'])) {
  118. $address_info['query'] = '';
  119. } else {
  120. $address_info['query'] = '?' . $address_info['query'];
  121. }
  122. $this->_remoteHost = $address_info['host'];
  123. $this->_remotePort = $address_info['port'];
  124. $this->_remoteURI = "{$address_info['path']}{$address_info['query']}";
  125. $scheme = isset($address_info['scheme']) ? $address_info['scheme'] : 'tcp';
  126. $this->_remoteAddress = 'unix' === strtolower($scheme)
  127. ? substr($remote_address, strpos($remote_address, '/') + 2)
  128. : $this->_remoteHost . ':' . $this->_remotePort;
  129. }
  130. $this->id = $this->_id = self::$_idRecorder++;
  131. if(\PHP_INT_MAX === self::$_idRecorder){
  132. self::$_idRecorder = 0;
  133. }
  134. // Check application layer protocol class.
  135. if (!isset(self::$_builtinTransports[$scheme])) {
  136. $scheme = \ucfirst($scheme);
  137. $this->protocol = '\\Protocols\\' . $scheme;
  138. if (!\class_exists($this->protocol)) {
  139. $this->protocol = "\\Workerman\\Protocols\\$scheme";
  140. if (!\class_exists($this->protocol)) {
  141. throw new Exception("class \\Protocols\\$scheme not exist");
  142. }
  143. }
  144. } else {
  145. $this->transport = self::$_builtinTransports[$scheme];
  146. }
  147. // For statistics.
  148. ++self::$statistics['connection_count'];
  149. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  150. $this->maxPackageSize = self::$defaultMaxPackageSize;
  151. $this->_contextOption = $context_option;
  152. static::$connections[$this->_id] = $this;
  153. }
  154. /**
  155. * Do connect.
  156. *
  157. * @return void
  158. */
  159. public function connect()
  160. {
  161. if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING &&
  162. $this->_status !== self::STATUS_CLOSED) {
  163. return;
  164. }
  165. $this->_status = self::STATUS_CONNECTING;
  166. $this->_connectStartTime = \microtime(true);
  167. if ($this->transport !== 'unix') {
  168. if (!$this->_remotePort) {
  169. $this->_remotePort = $this->transport === 'ssl' ? 443 : 80;
  170. $this->_remoteAddress = $this->_remoteHost.':'.$this->_remotePort;
  171. }
  172. // Open socket connection asynchronously.
  173. if ($this->_contextOption) {
  174. $context = \stream_context_create($this->_contextOption);
  175. $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
  176. $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT, $context);
  177. } else {
  178. $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
  179. $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT);
  180. }
  181. } else {
  182. $this->_socket = \stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
  183. \STREAM_CLIENT_ASYNC_CONNECT);
  184. }
  185. // If failed attempt to emit onError callback.
  186. if (!$this->_socket || !\is_resource($this->_socket)) {
  187. $this->emitError(\WORKERMAN_CONNECT_FAIL, $errstr);
  188. if ($this->_status === self::STATUS_CLOSING) {
  189. $this->destroy();
  190. }
  191. if ($this->_status === self::STATUS_CLOSED) {
  192. $this->onConnect = null;
  193. }
  194. return;
  195. }
  196. // Add socket to global event loop waiting connection is successfully established or faild.
  197. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
  198. // For windows.
  199. if(\DIRECTORY_SEPARATOR === '\\') {
  200. Worker::$globalEvent->add($this->_socket, EventInterface::EV_EXCEPT, array($this, 'checkConnection'));
  201. }
  202. }
  203. /**
  204. * Reconnect.
  205. *
  206. * @param int $after
  207. * @return void
  208. */
  209. public function reconnect($after = 0)
  210. {
  211. $this->_status = self::STATUS_INITIAL;
  212. static::$connections[$this->_id] = $this;
  213. if ($this->_reconnectTimer) {
  214. Timer::del($this->_reconnectTimer);
  215. }
  216. if ($after > 0) {
  217. $this->_reconnectTimer = Timer::add($after, array($this, 'connect'), null, false);
  218. return;
  219. }
  220. $this->connect();
  221. }
  222. /**
  223. * CancelReconnect.
  224. */
  225. public function cancelReconnect()
  226. {
  227. if ($this->_reconnectTimer) {
  228. Timer::del($this->_reconnectTimer);
  229. }
  230. }
  231. /**
  232. * Get remote address.
  233. *
  234. * @return string
  235. */
  236. public function getRemoteHost()
  237. {
  238. return $this->_remoteHost;
  239. }
  240. /**
  241. * Get remote URI.
  242. *
  243. * @return string
  244. */
  245. public function getRemoteURI()
  246. {
  247. return $this->_remoteURI;
  248. }
  249. /**
  250. * Try to emit onError callback.
  251. *
  252. * @param int $code
  253. * @param string $msg
  254. * @return void
  255. */
  256. protected function emitError($code, $msg)
  257. {
  258. $this->_status = self::STATUS_CLOSING;
  259. if ($this->onError) {
  260. try {
  261. \call_user_func($this->onError, $this, $code, $msg);
  262. } catch (\Exception $e) {
  263. Worker::stopAll(250, $e);
  264. } catch (\Error $e) {
  265. Worker::stopAll(250, $e);
  266. }
  267. }
  268. }
  269. /**
  270. * Check connection is successfully established or faild.
  271. *
  272. * @param resource $socket
  273. * @return void
  274. */
  275. public function checkConnection()
  276. {
  277. // Remove EV_EXPECT for windows.
  278. if(\DIRECTORY_SEPARATOR === '\\') {
  279. Worker::$globalEvent->del($this->_socket, EventInterface::EV_EXCEPT);
  280. }
  281. // Remove write listener.
  282. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  283. if ($this->_status !== self::STATUS_CONNECTING) {
  284. return;
  285. }
  286. // Check socket state.
  287. if ($address = \stream_socket_get_name($this->_socket, true)) {
  288. // Nonblocking.
  289. \stream_set_blocking($this->_socket, false);
  290. // Compatible with hhvm
  291. if (\function_exists('stream_set_read_buffer')) {
  292. \stream_set_read_buffer($this->_socket, 0);
  293. }
  294. // Try to open keepalive for tcp and disable Nagle algorithm.
  295. if (\function_exists('socket_import_stream') && $this->transport === 'tcp') {
  296. $raw_socket = \socket_import_stream($this->_socket);
  297. \socket_set_option($raw_socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
  298. \socket_set_option($raw_socket, \SOL_TCP, \TCP_NODELAY, 1);
  299. }
  300. // SSL handshake.
  301. if ($this->transport === 'ssl') {
  302. $this->_sslHandshakeCompleted = $this->doSslHandshake($this->_socket);
  303. if ($this->_sslHandshakeCompleted === false) {
  304. return;
  305. }
  306. } else {
  307. // There are some data waiting to send.
  308. if ($this->_sendBuffer) {
  309. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  310. }
  311. }
  312. // Register a listener waiting read event.
  313. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  314. $this->_status = self::STATUS_ESTABLISHED;
  315. $this->_remoteAddress = $address;
  316. // Try to emit onConnect callback.
  317. if ($this->onConnect) {
  318. try {
  319. \call_user_func($this->onConnect, $this);
  320. } catch (\Exception $e) {
  321. Worker::stopAll(250, $e);
  322. } catch (\Error $e) {
  323. Worker::stopAll(250, $e);
  324. }
  325. }
  326. // Try to emit protocol::onConnect
  327. if ($this->protocol && \method_exists($this->protocol, 'onConnect')) {
  328. try {
  329. \call_user_func(array($this->protocol, 'onConnect'), $this);
  330. } catch (\Exception $e) {
  331. Worker::stopAll(250, $e);
  332. } catch (\Error $e) {
  333. Worker::stopAll(250, $e);
  334. }
  335. }
  336. } else {
  337. // Connection failed.
  338. $this->emitError(\WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(\microtime(true) - $this->_connectStartTime, 4) . ' seconds');
  339. if ($this->_status === self::STATUS_CLOSING) {
  340. $this->destroy();
  341. }
  342. if ($this->_status === self::STATUS_CLOSED) {
  343. $this->onConnect = null;
  344. }
  345. }
  346. }
  347. }