AsyncTcpConnection.php 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. * Status.
  31. *
  32. * @var int
  33. */
  34. protected $_status = self::STATUS_CONNECTING;
  35. /**
  36. * Remote host.
  37. *
  38. * @var string
  39. */
  40. protected $_remoteHost = '';
  41. /**
  42. * Construct.
  43. *
  44. * @param string $remote_address
  45. * @throws Exception
  46. */
  47. public function __construct($remote_address)
  48. {
  49. list($scheme, $address) = explode(':', $remote_address, 2);
  50. if ($scheme != 'tcp') {
  51. // Get application layer protocol.
  52. $scheme = ucfirst($scheme);
  53. $this->protocol = '\\Protocols\\' . $scheme;
  54. if (!class_exists($this->protocol)) {
  55. $this->protocol = '\\Workerman\\Protocols\\' . $scheme;
  56. if (!class_exists($this->protocol)) {
  57. throw new Exception("class \\Protocols\\$scheme not exist");
  58. }
  59. }
  60. }
  61. $this->_remoteAddress = substr($address, 2);
  62. $this->_remoteHost = substr($this->_remoteAddress, 0, strrpos($this->_remoteAddress, ':'));
  63. $this->id = self::$_idRecorder++;
  64. // For statistics.
  65. self::$statistics['connection_count']++;
  66. $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
  67. }
  68. public function connect()
  69. {
  70. // Open socket connection asynchronously.
  71. $this->_socket = stream_socket_client("tcp://{$this->_remoteAddress}", $errno, $errstr, 0,
  72. STREAM_CLIENT_ASYNC_CONNECT);
  73. // If failed attempt to emit onError callback.
  74. if (!$this->_socket) {
  75. $this->_status = self::STATUS_CLOSED;
  76. $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
  77. return;
  78. }
  79. // Add socket to global event loop waiting connection is successfully established or faild.
  80. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
  81. }
  82. /**
  83. * Get remote address.
  84. *
  85. * @return string
  86. */
  87. public function getRemoteHost()
  88. {
  89. return $this->_remoteHost;
  90. }
  91. /**
  92. * Try to emit onError callback.
  93. *
  94. * @param int $code
  95. * @param string $msg
  96. * @return void
  97. */
  98. protected function emitError($code, $msg)
  99. {
  100. if ($this->onError) {
  101. try {
  102. call_user_func($this->onError, $this, $code, $msg);
  103. } catch (\Exception $e) {
  104. echo $e;
  105. exit(250);
  106. }
  107. }
  108. }
  109. /**
  110. * Check connection is successfully established or faild.
  111. *
  112. * @param resource $socket
  113. * @return void
  114. */
  115. public function checkConnection($socket)
  116. {
  117. // Check socket state.
  118. if (stream_socket_get_name($socket, true)) {
  119. // Remove write listener.
  120. Worker::$globalEvent->del($socket, EventInterface::EV_WRITE);
  121. // Nonblocking.
  122. stream_set_blocking($socket, 0);
  123. // Try to open keepalive for tcp and disable Nagle algorithm.
  124. if (function_exists('socket_import_stream')) {
  125. $raw_socket = socket_import_stream($socket);
  126. socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  127. socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1);
  128. }
  129. // Register a listener waiting read event.
  130. Worker::$globalEvent->add($socket, EventInterface::EV_READ, array($this, 'baseRead'));
  131. // There are some data waiting to send.
  132. if ($this->_sendBuffer) {
  133. Worker::$globalEvent->add($socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  134. }
  135. $this->_status = self::STATUS_ESTABLISH;
  136. $this->_remoteAddress = stream_socket_get_name($socket, true);
  137. // Try to emit onConnect callback.
  138. if ($this->onConnect) {
  139. try {
  140. call_user_func($this->onConnect, $this);
  141. } catch (\Exception $e) {
  142. echo $e;
  143. exit(250);
  144. }
  145. }
  146. } else {
  147. // Connection failed.
  148. $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect fail');
  149. $this->destroy();
  150. $this->onConnect = null;
  151. }
  152. }
  153. }