Pārlūkot izejas kodu

AsyncTcpConnection support reConnect

walkor 9 gadi atpakaļ
vecāks
revīzija
013114daff
1 mainītis faili ar 29 papildinājumiem un 3 dzēšanām
  1. 29 3
      Connection/AsyncTcpConnection.php

+ 29 - 3
Connection/AsyncTcpConnection.php

@@ -14,6 +14,7 @@
 namespace Workerman\Connection;
 
 use Workerman\Events\EventInterface;
+use Workerman\Lib\Timer;
 use Workerman\Worker;
 use Exception;
 
@@ -67,10 +68,17 @@ class AsyncTcpConnection extends TcpConnection
     /**
      * Context option.
      *
-     * @var null
+     * @var resource
      */
     protected $_contextOption = null;
 
+    /**
+     * Reconnect timer.
+     *
+     * @var int
+     */
+    protected $_reconnectTimer = null;
+
 
     /**
      * PHP built-in protocols.
@@ -146,11 +154,11 @@ class AsyncTcpConnection extends TcpConnection
      */
     public function connect()
     {
-         if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING &&
+        if ($this->_status !== self::STATUS_INITIAL && $this->_status !== self::STATUS_CLOSING &&
              $this->_status !== self::STATUS_CLOSED) {
             return;
         }
-        $this->_status = self::STATUS_CONNECTING;
+        $this->_status           = self::STATUS_CONNECTING;
         $this->_connectStartTime = microtime(true);
         // Open socket connection asynchronously.
         if ($this->_contextOption) {
@@ -177,6 +185,24 @@ class AsyncTcpConnection extends TcpConnection
     }
 
     /**
+     * Reconnect.
+     *
+     * @param int $after
+     * @return void
+     */
+    public function reConnect($after = 0) {
+        $this->_status = self::STATUS_INITIAL;
+        if ($this->_reconnectTimer) {
+            Timer::del($this->_reconnectTimer);
+        }
+        if ($after >= 0) {
+            $this->_reconnectTimer = Timer::add($after, array($this, 'connect'), null, false);
+            return;
+        }
+        return $this->connect();
+    }
+
+    /**
      * Get remote address.
      *
      * @return string