AsyncTcpConnection.php 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. * Construct.
  37. *
  38. * @param string $remote_address
  39. * @throws Exception
  40. */
  41. public function __construct($remote_address)
  42. {
  43. list($scheme, $address) = explode(':', $remote_address, 2);
  44. if ($scheme != 'tcp') {
  45. // Get application layer protocol.
  46. $scheme = ucfirst($scheme);
  47. $this->protocol = '\\Protocols\\' . $scheme;
  48. if (!class_exists($this->protocol)) {
  49. $this->protocol = '\\Workerman\\Protocols\\' . $scheme;
  50. if (!class_exists($this->protocol)) {
  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,
  65. STREAM_CLIENT_ASYNC_CONNECT);
  66. // If failed attempt to emit onError callback.
  67. if (!$this->_socket) {
  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. *
  78. * @param int $code
  79. * @param string $msg
  80. * @return void
  81. */
  82. protected function emitError($code, $msg)
  83. {
  84. if ($this->onError) {
  85. try {
  86. call_user_func($this->onError, $this, $code, $msg);
  87. } catch (\Exception $e) {
  88. echo $e;
  89. exit(250);
  90. }
  91. }
  92. }
  93. /**
  94. * Check connection is successfully established or faild.
  95. *
  96. * @param resource $socket
  97. * @return void
  98. */
  99. public function checkConnection($socket)
  100. {
  101. // Need call foef twice.
  102. if (!feof($this->_socket) && !feof($this->_socket) && is_resource($this->_socket)) {
  103. // Remove write listener.
  104. Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
  105. // Nonblocking.
  106. stream_set_blocking($this->_socket, 0);
  107. // Try to open keepalive for tcp and disable Nagle algorithm.
  108. if (function_exists('socket_import_stream')) {
  109. $raw_socket = socket_import_stream($this->_socket);
  110. socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1);
  111. socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1);
  112. }
  113. // Register a listener waiting read event.
  114. Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
  115. // There are some data waiting to send.
  116. if ($this->_sendBuffer) {
  117. Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
  118. }
  119. $this->_status = self::STATUS_ESTABLISH;
  120. $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
  121. // Try to emit onConnect callback.
  122. if ($this->onConnect) {
  123. try {
  124. call_user_func($this->onConnect, $this);
  125. } catch (\Exception $e) {
  126. echo $e;
  127. exit(250);
  128. }
  129. }
  130. } else {
  131. // Connection failed.
  132. $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect fail');
  133. $this->destroy();
  134. $this->onConnect = null;
  135. }
  136. }
  137. }