AsyncTcpConnection.php 10 KB

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