AsyncTcpConnection.php 12 KB

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