AsyncTcpConnection.php 9.9 KB

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