AsyncTcpConnection.php 9.3 KB

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