AsyncTcpConnection.php 4.8 KB

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