AsyncTcpConnection.php 8.8 KB

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