Bläddra i källkod

Merge pull request #1 from walkor/master

同步最新
hkui 5 år sedan
förälder
incheckning
4284726d47

+ 3 - 3
Autoloader.php

@@ -44,15 +44,15 @@ class Autoloader
      */
     public static function loadByNamespace($name)
     {
-        $class_path = \str_replace('\\', DIRECTORY_SEPARATOR, $name);
+        $class_path = \str_replace('\\', \DIRECTORY_SEPARATOR, $name);
         if (\strpos($name, 'Workerman\\') === 0) {
             $class_file = __DIR__ . \substr($class_path, \strlen('Workerman')) . '.php';
         } else {
             if (self::$_autoloadRootPath) {
-                $class_file = self::$_autoloadRootPath . DIRECTORY_SEPARATOR . $class_path . '.php';
+                $class_file = self::$_autoloadRootPath . \DIRECTORY_SEPARATOR . $class_path . '.php';
             }
             if (empty($class_file) || !\is_file($class_file)) {
-                $class_file = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . "$class_path.php";
+                $class_file = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . "$class_path.php";
             }
         }
 

+ 18 - 13
Connection/AsyncTcpConnection.php

@@ -16,7 +16,7 @@ namespace Workerman\Connection;
 use Workerman\Events\EventInterface;
 use Workerman\Lib\Timer;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 /**
  * AsyncTcpConnection.
@@ -119,7 +119,7 @@ class AsyncTcpConnection extends TcpConnection
             }
         } else {
             if (!isset($address_info['port'])) {
-                $address_info['port'] = 80;
+                $address_info['port'] = 0;
             }
             if (!isset($address_info['path'])) {
                 $address_info['path'] = '/';
@@ -137,7 +137,7 @@ class AsyncTcpConnection extends TcpConnection
         }
 
         $this->id = $this->_id = self::$_idRecorder++;
-        if(PHP_INT_MAX === self::$_idRecorder){
+        if(\PHP_INT_MAX === self::$_idRecorder){
             self::$_idRecorder = 0;
         }
         // Check application layer protocol class.
@@ -155,8 +155,9 @@ class AsyncTcpConnection extends TcpConnection
         }
 
         // For statistics.
-        self::$statistics['connection_count']++;
+        ++self::$statistics['connection_count'];
         $this->maxSendBufferSize         = self::$defaultMaxSendBufferSize;
+        $this->maxPackageSize            = self::$defaultMaxPackageSize;
         $this->_contextOption            = $context_option;
         static::$connections[$this->_id] = $this;
     }
@@ -175,22 +176,26 @@ class AsyncTcpConnection extends TcpConnection
         $this->_status           = self::STATUS_CONNECTING;
         $this->_connectStartTime = \microtime(true);
         if ($this->transport !== 'unix') {
+            if (!$this->_remotePort) {
+                $this->_remotePort = $this->transport === 'ssl' ? 443 : 80;
+                $this->_remoteAddress = $this->_remoteHost.':'.$this->_remotePort;
+            }
             // Open socket connection asynchronously.
             if ($this->_contextOption) {
                 $context = \stream_context_create($this->_contextOption);
                 $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
-                    $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT, $context);
+                    $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT, $context);
             } else {
                 $this->_socket = \stream_socket_client("tcp://{$this->_remoteHost}:{$this->_remotePort}",
-                    $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT);
+                    $errno, $errstr, 0, \STREAM_CLIENT_ASYNC_CONNECT);
             }
         } else {
             $this->_socket = \stream_socket_client("{$this->transport}://{$this->_remoteAddress}", $errno, $errstr, 0,
-                STREAM_CLIENT_ASYNC_CONNECT);
+                \STREAM_CLIENT_ASYNC_CONNECT);
         }
         // If failed attempt to emit onError callback.
         if (!$this->_socket || !\is_resource($this->_socket)) {
-            $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
+            $this->emitError(\WORKERMAN_CONNECT_FAIL, $errstr);
             if ($this->_status === self::STATUS_CLOSING) {
                 $this->destroy();
             }
@@ -202,7 +207,7 @@ class AsyncTcpConnection extends TcpConnection
         // Add socket to global event loop waiting connection is successfully established or faild.
         Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
         // For windows.
-        if(DIRECTORY_SEPARATOR === '\\') {
+        if(\DIRECTORY_SEPARATOR === '\\') {
             Worker::$globalEvent->add($this->_socket, EventInterface::EV_EXCEPT, array($this, 'checkConnection'));
         }
     }
@@ -289,7 +294,7 @@ class AsyncTcpConnection extends TcpConnection
     public function checkConnection()
     {
         // Remove EV_EXPECT for windows.
-        if(DIRECTORY_SEPARATOR === '\\') {
+        if(\DIRECTORY_SEPARATOR === '\\') {
             Worker::$globalEvent->del($this->_socket, EventInterface::EV_EXCEPT);
         }
 
@@ -311,8 +316,8 @@ class AsyncTcpConnection extends TcpConnection
             // Try to open keepalive for tcp and disable Nagle algorithm.
             if (\function_exists('socket_import_stream') && $this->transport === 'tcp') {
                 $raw_socket = \socket_import_stream($this->_socket);
-                \socket_set_option($raw_socket, SOL_SOCKET, SO_KEEPALIVE, 1);
-                \socket_set_option($raw_socket, SOL_TCP, TCP_NODELAY, 1);
+                \socket_set_option($raw_socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
+                \socket_set_option($raw_socket, \SOL_TCP, \TCP_NODELAY, 1);
             }
 
             // SSL handshake.
@@ -360,7 +365,7 @@ class AsyncTcpConnection extends TcpConnection
             }
         } else {
             // Connection failed.
-            $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(\microtime(true) - $this->_connectStartTime, 4) . ' seconds');
+            $this->emitError(\WORKERMAN_CONNECT_FAIL, 'connect ' . $this->_remoteAddress . ' fail after ' . round(\microtime(true) - $this->_connectStartTime, 4) . ' seconds');
             if ($this->_status === self::STATUS_CLOSING) {
                 $this->destroy();
             }

+ 3 - 3
Connection/AsyncUdpConnection.php

@@ -15,7 +15,7 @@ namespace Workerman\Connection;
 
 use Workerman\Events\EventInterface;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 /**
  * AsyncTcpConnection.
@@ -94,7 +94,7 @@ class AsyncUdpConnection extends UdpConnection
                 $parser      = $this->protocol;
                 $recv_buffer = $parser::decode($recv_buffer, $this);
             }
-            ConnectionInterface::$statistics['total_request']++;
+            ++ConnectionInterface::$statistics['total_request'];
             try {
                 \call_user_func($this->onMessage, $this, $recv_buffer);
             } catch (\Exception $e) {
@@ -176,7 +176,7 @@ class AsyncUdpConnection extends UdpConnection
         if ($this->_contextOption) {
             $context = \stream_context_create($this->_contextOption);
             $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg,
-                30, STREAM_CLIENT_CONNECT, $context);
+                30, \STREAM_CLIENT_CONNECT, $context);
         } else {
             $this->_socket = \stream_socket_client("udp://{$this->_remoteAddress}", $errno, $errmsg);
         }

+ 37 - 33
Connection/TcpConnection.php

@@ -15,7 +15,7 @@ namespace Workerman\Connection;
 
 use Workerman\Events\EventInterface;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 /**
  * TcpConnection.
@@ -292,9 +292,9 @@ class TcpConnection extends ConnectionInterface
      */
     public function __construct($socket, $remote_address = '')
     {
-        self::$statistics['connection_count']++;
+        ++self::$statistics['connection_count'];
         $this->id = $this->_id = self::$_idRecorder++;
-        if(self::$_idRecorder === PHP_INT_MAX){
+        if(self::$_idRecorder === \PHP_INT_MAX){
             self::$_idRecorder = 0;
         }
         $this->_socket = $socket;
@@ -315,7 +315,7 @@ class TcpConnection extends ConnectionInterface
      *
      * @param bool $raw_output
      *
-     * @return int
+     * @return int|string
      */
     public function getStatus($raw_output = true)
     {
@@ -351,7 +351,7 @@ class TcpConnection extends ConnectionInterface
             ($this->transport === 'ssl' && $this->_sslHandshakeCompleted !== true)
         ) {
             if ($this->_sendBuffer && $this->bufferIsFull()) {
-                self::$statistics['send_fail']++;
+                ++self::$statistics['send_fail'];
                 return false;
             }
             $this->_sendBuffer .= $send_buffer;
@@ -382,10 +382,10 @@ class TcpConnection extends ConnectionInterface
             } else {
                 // Connection closed?
                 if (!\is_resource($this->_socket) || \feof($this->_socket)) {
-                    self::$statistics['send_fail']++;
+                    ++self::$statistics['send_fail'];
                     if ($this->onError) {
                         try {
-                            \call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'client closed');
+                            \call_user_func($this->onError, $this, \WORKERMAN_SEND_FAIL, 'client closed');
                         } catch (\Exception $e) {
                             Worker::log($e);
                             exit(250);
@@ -403,16 +403,16 @@ class TcpConnection extends ConnectionInterface
             // Check if the send buffer will be full.
             $this->checkBufferWillFull();
             return;
-        } else {
-            if ($this->bufferIsFull()) {
-                self::$statistics['send_fail']++;
-                return false;
-            }
+        }
 
-            $this->_sendBuffer .= $send_buffer;
-            // Check if the send buffer is full.
-            $this->checkBufferWillFull();
+        if ($this->bufferIsFull()) {
+            ++self::$statistics['send_fail'];
+            return false;
         }
+
+        $this->_sendBuffer .= $send_buffer;
+        // Check if the send buffer is full.
+        $this->checkBufferWillFull();
     }
 
     /**
@@ -424,7 +424,7 @@ class TcpConnection extends ConnectionInterface
     {
         $pos = \strrpos($this->_remoteAddress, ':');
         if ($pos) {
-            return \substr($this->_remoteAddress, 0, $pos);
+            return (string) \substr($this->_remoteAddress, 0, $pos);
         }
         return '';
     }
@@ -437,7 +437,7 @@ class TcpConnection extends ConnectionInterface
     public function getRemotePort()
     {
         if ($this->_remoteAddress) {
-            return (int)\substr(\strrchr($this->_remoteAddress, ':'), 1);
+            return (int) \substr(\strrchr($this->_remoteAddress, ':'), 1);
         }
         return 0;
     }
@@ -601,6 +601,7 @@ class TcpConnection extends ConnectionInterface
             $this->_recvBuffer .= $buffer;
         }
 
+        $recv_len = \strlen($this->_recvBuffer);
         // If the application layer protocol has been set up.
         if ($this->protocol !== null) {
             $parser = $this->protocol;
@@ -608,7 +609,7 @@ class TcpConnection extends ConnectionInterface
                 // The current packet length is known.
                 if ($this->_currentPackageLength) {
                     // Data is not enough for a package.
-                    if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
+                    if ($this->_currentPackageLength > $recv_len) {
                         break;
                     }
                 } else {
@@ -623,21 +624,21 @@ class TcpConnection extends ConnectionInterface
                         break;
                     } elseif ($this->_currentPackageLength > 0 && $this->_currentPackageLength <= $this->maxPackageSize) {
                         // Data is not enough for a package.
-                        if ($this->_currentPackageLength > \strlen($this->_recvBuffer)) {
+                        if ($this->_currentPackageLength > $recv_len) {
                             break;
                         }
                     } // Wrong package.
                     else {
-                        Worker::safeEcho('error package. package_length=' . var_export($this->_currentPackageLength, true));
+                        Worker::safeEcho('Error package. package_length=' . \var_export($this->_currentPackageLength, true));
                         $this->destroy();
                         return;
                     }
                 }
 
                 // The data is enough for a packet.
-                self::$statistics['total_request']++;
+                ++self::$statistics['total_request'];
                 // The current packet length is equal to the length of the buffer.
-                if (\strlen($this->_recvBuffer) === $this->_currentPackageLength) {
+                if ($recv_len === $this->_currentPackageLength) {
                     $one_request_buffer = $this->_recvBuffer;
                     $this->_recvBuffer  = '';
                 } else {
@@ -670,7 +671,7 @@ class TcpConnection extends ConnectionInterface
         }
 
         // Applications protocol is not set.
-        self::$statistics['total_request']++;
+        ++self::$statistics['total_request'];
         if (!$this->onMessage) {
             $this->_recvBuffer = '';
             return;
@@ -727,7 +728,7 @@ class TcpConnection extends ConnectionInterface
             $this->bytesWritten += $len;
             $this->_sendBuffer = \substr($this->_sendBuffer, $len);
         } else {
-            self::$statistics['send_fail']++;
+            ++self::$statistics['send_fail'];
             $this->destroy();
         }
     }
@@ -756,9 +757,9 @@ class TcpConnection extends ConnectionInterface
         }*/
         
         if($async){
-            $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
+            $type = \STREAM_CRYPTO_METHOD_SSLv2_CLIENT | \STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
         }else{
-            $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER;
+            $type = \STREAM_CRYPTO_METHOD_SSLv2_SERVER | \STREAM_CRYPTO_METHOD_SSLv23_SERVER;
         }
         
         // Hidden error.
@@ -838,14 +839,17 @@ class TcpConnection extends ConnectionInterface
             $this->destroy();
             return;
         }
+
         if ($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED) {
             return;
-        } else {
-            if ($data !== null) {
-                $this->send($data, $raw);
-            }
-            $this->_status = self::STATUS_CLOSING;
         }
+
+        if ($data !== null) {
+            $this->send($data, $raw);
+        }
+
+        $this->_status = self::STATUS_CLOSING;
+        
         if ($this->_sendBuffer === '') {
             $this->destroy();
         } else {
@@ -896,7 +900,7 @@ class TcpConnection extends ConnectionInterface
         if ($this->maxSendBufferSize <= \strlen($this->_sendBuffer)) {
             if ($this->onError) {
                 try {
-                    \call_user_func($this->onError, $this, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
+                    \call_user_func($this->onError, $this, \WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
                 } catch (\Exception $e) {
                     Worker::log($e);
                     exit(250);
@@ -988,7 +992,7 @@ class TcpConnection extends ConnectionInterface
         self::$statistics['connection_count']--;
         if (Worker::getGracefulStop()) {
             if (!isset($mod)) {
-                $mod = ceil((self::$statistics['connection_count'] + 1) / 3);
+                $mod = \ceil((self::$statistics['connection_count'] + 1) / 3);
             }
 
             if (0 === self::$statistics['connection_count'] % $mod) {

+ 1 - 1
Events/Ev.php

@@ -13,7 +13,7 @@
 namespace Workerman\Events;
 
 use Workerman\Worker;
-use EvWatcher;
+use \EvWatcher;
 
 /**
  * ev eventloop

+ 5 - 5
Events/Libevent.php

@@ -54,7 +54,7 @@ class Libevent implements EventInterface
      */
     public function __construct()
     {
-        $this->_eventBase = event_base_new();
+        $this->_eventBase = \event_base_new();
     }
 
     /**
@@ -65,8 +65,8 @@ class Libevent implements EventInterface
         switch ($flag) {
             case self::EV_SIGNAL:
                 $fd_key                      = (int)$fd;
-                $real_flag                   = EV_SIGNAL | EV_PERSIST;
-                $this->_eventSignal[$fd_key] = event_new();
+                $real_flag                   = \EV_SIGNAL | \EV_PERSIST;
+                $this->_eventSignal[$fd_key] = \event_new();
                 if (!\event_set($this->_eventSignal[$fd_key], $fd, $real_flag, $func, null)) {
                     return false;
                 }
@@ -81,7 +81,7 @@ class Libevent implements EventInterface
             case self::EV_TIMER_ONCE:
                 $event    = \event_new();
                 $timer_id = (int)$event;
-                if (!\event_set($event, 0, EV_TIMEOUT, array($this, 'timerCallback'), $timer_id)) {
+                if (!\event_set($event, 0, \EV_TIMEOUT, array($this, 'timerCallback'), $timer_id)) {
                     return false;
                 }
 
@@ -98,7 +98,7 @@ class Libevent implements EventInterface
 
             default :
                 $fd_key    = (int)$fd;
-                $real_flag = $flag === self::EV_READ ? EV_READ | EV_PERSIST : EV_WRITE | EV_PERSIST;
+                $real_flag = $flag === self::EV_READ ? \EV_READ | \EV_PERSIST : \EV_WRITE | \EV_PERSIST;
 
                 $event = \event_new();
 

+ 13 - 15
Events/Select.php

@@ -95,13 +95,6 @@ class Select implements EventInterface
      */
     public function __construct()
     {
-        // Create a pipeline and put into the collection of the read to read the descriptor to avoid empty polling.
-        $this->channel = \stream_socket_pair(DIRECTORY_SEPARATOR === '/' ? STREAM_PF_UNIX : STREAM_PF_INET,
-            STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
-        if($this->channel) {
-            \stream_set_blocking($this->channel[0], 0);
-            $this->_readFds[0] = $this->channel[0];
-        }
         // Init SplPriorityQueue.
         $this->_scheduler = new \SplPriorityQueue();
         $this->_scheduler->setExtractFlags(\SplPriorityQueue::EXTR_BOTH);
@@ -118,7 +111,7 @@ class Select implements EventInterface
                 $count = $flag === self::EV_READ ? \count($this->_readFds) : \count($this->_writeFds);
                 if ($count >= 1024) {
                     echo "Warning: system call select exceeded the maximum number of connections 1024, please install event/libevent extension for more connections.\n";
-                } else if (DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
+                } else if (\DIRECTORY_SEPARATOR !== '/' && $count >= 256) {
                     echo "Warning: system call select exceeded the maximum number of connections 256.\n";
                 }
                 $fd_key                           = (int)$fd;
@@ -136,7 +129,7 @@ class Select implements EventInterface
                 break;
             case self::EV_SIGNAL:
                 // Windows not support signal.
-                if(DIRECTORY_SEPARATOR !== '/') {
+                if(\DIRECTORY_SEPARATOR !== '/') {
                     return false;
                 }
                 $fd_key                              = (int)$fd;
@@ -196,7 +189,7 @@ class Select implements EventInterface
                 }
                 return true;
             case self::EV_SIGNAL:
-                if(DIRECTORY_SEPARATOR !== '/') {
+                if(\DIRECTORY_SEPARATOR !== '/') {
                     return false;
                 }
                 unset($this->_signalEvents[$fd_key]);
@@ -263,7 +256,7 @@ class Select implements EventInterface
     public function loop()
     {
         while (1) {
-            if(DIRECTORY_SEPARATOR === '/') {
+            if(\DIRECTORY_SEPARATOR === '/') {
                 // Calls signal handlers for pending signals
                 \pcntl_signal_dispatch();
             }
@@ -272,10 +265,15 @@ class Select implements EventInterface
             $write = $this->_writeFds;
             $except = $this->_exceptFds;
 
-            // Waiting read/write/signal/timeout events.
-            \set_error_handler(function(){});
-            $ret = stream_select($read, $write, $except, 0, $this->_selectTimeout);
-            \restore_error_handler();
+            if ($read || $write || $except) {
+                // Waiting read/write/signal/timeout events.
+                set_error_handler(function(){});
+                $ret = stream_select($read, $write, $except, 0, $this->_selectTimeout);
+                restore_error_handler();
+            } else {
+                usleep($this->_selectTimeout);
+                $ret = false;
+            }
 
 
             if (!$this->_scheduler->isEmpty()) {

+ 2 - 2
Events/Swoole.php

@@ -57,7 +57,7 @@ class Swoole implements EventInterface
             case self::EV_TIMER:
             case self::EV_TIMER_ONCE:
                 $method = self::EV_TIMER === $flag ? 'tick' : 'after';
-                if ($this->mapId > PHP_INT_MAX) {
+                if ($this->mapId > \PHP_INT_MAX) {
                     $this->mapId = 0;
                 }
                 $mapId = $this->mapId++;
@@ -67,7 +67,7 @@ class Swoole implements EventInterface
                         // EV_TIMER_ONCE
                         if (! isset($timer_id)) {
                             // may be deleted in $func
-                            if (array_key_exists($mapId, $this->_timerOnceMap)) {
+                            if (\array_key_exists($mapId, $this->_timerOnceMap)) {
                                 $timer_id = $this->_timerOnceMap[$mapId];
                                 unset($this->_timer[$timer_id],
                                     $this->_timerOnceMap[$mapId]);

+ 9 - 12
Lib/Constants.php

@@ -8,32 +8,29 @@
  *
  * @author    walkor<walkor@workerman.net>
  * @copyright walkor<walkor@workerman.net>
- * @link      http://www.workerman.net/
  * @license   http://www.opensource.org/licenses/mit-license.php MIT License
+ *
+ * @link      http://www.workerman.net/
  */
 
 // Display errors.
 ini_set('display_errors', 'on');
 // Reporting all.
 error_reporting(E_ALL);
-
-// Reset opcache.
-if (function_exists('opcache_reset')) {
-    opcache_reset();
-}
+// JIT is not stable, temporarily disabled.
+ini_set('pcre.jit', 0);
 
 // For onError callback.
-define('WORKERMAN_CONNECT_FAIL', 1);
+const WORKERMAN_CONNECT_FAIL = 1;
 // For onError callback.
-define('WORKERMAN_SEND_FAIL', 2);
+const WORKERMAN_SEND_FAIL = 2;
 
 // Define OS Type
-define('OS_TYPE_LINUX', 'linux');
-define('OS_TYPE_WINDOWS', 'windows');
+const OS_TYPE_LINUX   = 'linux';
+const OS_TYPE_WINDOWS = 'windows';
 
 // Compatible with php7
-if(!class_exists('Error'))
-{
+if ( ! class_exists('Error')) {
     class Error extends Exception
     {
     }

+ 10 - 7
Lib/Timer.php

@@ -15,7 +15,7 @@ namespace Workerman\Lib;
 
 use Workerman\Events\EventInterface;
 use Workerman\Worker;
-use Exception;
+use \Exception;
 
 /**
  * Timer.
@@ -54,10 +54,10 @@ class Timer
     {
         if ($event) {
             self::$_event = $event;
-        } else {
-            if (\function_exists('pcntl_signal')) {
-                \pcntl_signal(SIGALRM, array('\Workerman\Lib\Timer', 'signalHandle'), false);
-            }
+            return;
+        }
+        if (\function_exists('pcntl_signal')) {
+            \pcntl_signal(\SIGALRM, array('\Workerman\Lib\Timer', 'signalHandle'), false);
         }
     }
 
@@ -90,6 +90,10 @@ class Timer
             return false;
         }
 
+        if ($args === null) {
+            $args = array();
+        }
+
         if (self::$_event) {
             return self::$_event->add($time_interval,
                 $persistent ? EventInterface::EV_TIMER : EventInterface::EV_TIMER_ONCE, $func, $args);
@@ -104,8 +108,7 @@ class Timer
             \pcntl_alarm(1);
         }
 
-        $time_now = \time();
-        $run_time = $time_now + $time_interval;
+        $run_time = \time() + $time_interval;
         if (!isset(self::$_tasks[$run_time])) {
             self::$_tasks[$run_time] = array();
         }

+ 103 - 68
Protocols/Http.php

@@ -26,7 +26,13 @@ class Http
       * The supported HTTP methods
       * @var array
       */
-    public static $methods = array('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS');
+    public static $methods = array('GET'=>'GET', 'POST'=>'POST', 'PUT'=>'PUT', 'DELETE'=>'DELETE', 'HEAD'=>'HEAD', 'OPTIONS'=>'OPTIONS');
+
+    /**
+     * Cache.
+     * @var array
+     */
+    protected static $_cache = array();
 
     /**
      * Check the integrity of the package.
@@ -37,43 +43,41 @@ class Http
      */
     public static function input($recv_buffer, TcpConnection $connection)
     {
-        if (!\strpos($recv_buffer, "\r\n\r\n")) {
+        if (isset(static::$_cache[$recv_buffer]['input'])) {
+            return static::$_cache[$recv_buffer]['input'];
+        }
+        $recv_len = \strlen($recv_buffer);
+        $crlf_post = \strpos($recv_buffer, "\r\n\r\n");
+        if (!$crlf_post) {
             // Judge whether the package length exceeds the limit.
-            if (\strlen($recv_buffer) >= $connection->maxPackageSize) {
+            if ($recv_len >= $connection->maxPackageSize) {
                 $connection->close();
             }
             return 0;
         }
+        $head_len = $crlf_post + 4;
 
-        list($header,) = \explode("\r\n\r\n", $recv_buffer, 2);
-        $method = \substr($header, 0, \strpos($header, ' '));
-
-        if(\in_array($method, static::$methods)) {
-            return static::getRequestSize($header, $method);
+        $method = \substr($recv_buffer, 0, \strpos($recv_buffer, ' '));
+        if (!isset(static::$methods[$method])) {
+            $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n", true);
+            $connection->consumeRecvBuffer($recv_len);
+            return 0;
         }
 
-        $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n", true);
-        return 0;
-    }
-
-    /**
-      * Get whole size of the request
-      * includes the request headers and request body.
-      * @param string $header The request headers
-      * @param string $method The request method
-      * @return integer
-      */
-    protected static function getRequestSize($header, $method)
-    {
-        if($method === 'GET' || $method === 'OPTIONS' || $method === 'HEAD') {
-            return \strlen($header) + 4;
+        if ($method === 'GET' || $method === 'OPTIONS' || $method === 'HEAD') {
+            static::$_cache[$recv_buffer]['input'] = $head_len;
+            return $head_len;
         }
+
         $match = array();
-        if (\preg_match("/\r\nContent-Length: ?(\d+)/i", $header, $match)) {
+        if (\preg_match("/\r\nContent-Length: ?(\d+)/i", $recv_buffer, $match)) {
             $content_length = isset($match[1]) ? $match[1] : 0;
-            return $content_length + \strlen($header) + 4;
+            $total_length = $content_length + $head_len;
+            static::$_cache[$recv_buffer]['input'] = $total_length;
+            return $total_length;
         }
-        return $method === 'DELETE' ? \strlen($header) + 4 : 0;
+
+        return $method === 'DELETE' ? $head_len : 0;
     }
 
     /**
@@ -85,13 +89,25 @@ class Http
      */
     public static function decode($recv_buffer, TcpConnection $connection)
     {
+        if (isset(static::$_cache[$recv_buffer]['decode'])) {
+            HttpCache::reset();
+            $cache = static::$_cache[$recv_buffer]['decode'];
+            //$cache['server']['REQUEST_TIME_FLOAT'] =  \microtime(true);
+            //$cache['server']['REQUEST_TIME'] =  (int)$cache['server']['REQUEST_TIME_FLOAT'];
+            $_SERVER = $cache['server'];
+            $_POST = $cache['post'];
+            $_GET = $cache['get'];
+            $_COOKIE = $cache['cookie'];
+            $_REQUEST = $cache['request'];
+            $GLOBALS['HTTP_RAW_POST_DATA'] = $GLOBALS['HTTP_RAW_REQUEST_DATA'] = '';
+            return static::$_cache[$recv_buffer]['decode'];
+        }
         // Init.
-        $_POST                         = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
+        $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES = array();
         $GLOBALS['HTTP_RAW_POST_DATA'] = '';
         // Clear cache.
-        HttpCache::$header   = HttpCache::$default;
-        HttpCache::$cookie   = array();
-        HttpCache::$instance = new HttpCache();
+        HttpCache::reset();
+        //$microtime = \microtime(true);
         // $_SERVER
         $_SERVER = array(
             'QUERY_STRING'         => '',
@@ -110,8 +126,8 @@ class Http
             'CONTENT_TYPE'         => '',
             'REMOTE_ADDR'          => '',
             'REMOTE_PORT'          => '0',
-            'REQUEST_TIME'         => \time(),
-            'REQUEST_TIME_FLOAT'   => \microtime(true) //compatible php5.4
+            //'REQUEST_TIME'         => (int)$microtime,
+            //'REQUEST_TIME_FLOAT'   => $microtime //compatible php5.4
         );
 
         // Parse headers.
@@ -169,23 +185,19 @@ class Http
                     break;
             }
         }
-		if(isset($_SERVER['HTTP_ACCEPT_ENCODING']) && \strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false){
-			HttpCache::$gzip = true;
-		}
+
         // Parse $_POST.
-        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
-            if (isset($_SERVER['CONTENT_TYPE'])) {
-                switch ($_SERVER['CONTENT_TYPE']) {
-                    case 'multipart/form-data':
-                        self::parseUploadFiles($http_body, $http_post_boundary);
-                        break;
-                    case 'application/json':
-                        $_POST = \json_decode($http_body, true);
-                        break;
-                    case 'application/x-www-form-urlencoded':
-                        \parse_str($http_body, $_POST);
-                        break;
-                }
+        if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['CONTENT_TYPE']) {
+            switch ($_SERVER['CONTENT_TYPE']) {
+                case 'multipart/form-data':
+                    self::parseUploadFiles($http_body, $http_post_boundary);
+                    break;
+                case 'application/json':
+                    $_POST = \json_decode($http_body, true);
+                    break;
+                case 'application/x-www-form-urlencoded':
+                    \parse_str($http_body, $_POST);
+                    break;
             }
         }
 
@@ -204,7 +216,7 @@ class Http
         $GLOBALS['HTTP_RAW_REQUEST_DATA'] = $GLOBALS['HTTP_RAW_POST_DATA'] = $http_body;
 
         // QUERY_STRING
-        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
+        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], \PHP_URL_QUERY);
         if ($_SERVER['QUERY_STRING']) {
             // $GET
             \parse_str($_SERVER['QUERY_STRING'], $_GET);
@@ -223,8 +235,15 @@ class Http
         // REMOTE_ADDR REMOTE_PORT
         $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
         $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
+        $ret = array('get' => $_GET, 'post' => $_POST, 'cookie' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES, 'request'=>$_REQUEST);
+        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
+            static::$_cache[$recv_buffer]['decode'] = $ret;
+            if (\count(static::$_cache) > 256) {
+                unset(static::$_cache[key(static::$_cache)]);
+            }
+        }
 
-        return array('get' => $_GET, 'post' => $_POST, 'cookie' => $_COOKIE, 'server' => $_SERVER, 'files' => $_FILES);
+        return $ret;
     }
 
     /**
@@ -237,8 +256,7 @@ class Http
     public static function encode($content, TcpConnection $connection)
     {
         // http-code status line.
-        $header = (HttpCache::$status ?: 'HTTP/1.1 200 OK') . "\r\n";
-        HttpCache::$status = '';
+        $header = HttpCache::$status . "\r\n";
 
         // Cookie headers
         if(HttpCache::$cookie) {
@@ -246,11 +264,13 @@ class Http
         }
         
         // other headers
-        $header .= \implode("\r\n", HttpCache::$header) . "\r\n";
+        if (HttpCache::$header) {
+            $header .= \implode("\r\n", HttpCache::$header) . "\r\n";
+        }
 
-        if(HttpCache::$gzip && isset($connection->gzip) && $connection->gzip){
-                $header .= "Content-Encoding: gzip\r\n";
-                $content = \gzencode($content,$connection->gzip);
+        if(!empty($connection->gzip)) {
+            $header .= "Content-Encoding: gzip\r\n";
+            $content = \gzencode($content,$connection->gzip);
         }
         // header
         $header .= 'Content-Length: ' . \strlen($content) . "\r\n\r\n";
@@ -273,7 +293,7 @@ class Http
      */
     public static function header($content, $replace = true, $http_response_code = null)
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             \header($content, $replace, $http_response_code);
             return;
         }
@@ -283,7 +303,7 @@ class Http
             return true;
         }
 
-        $key = \strstr($content, ":", true);
+        $key = \strstr($content, ':', true);
         if (empty($key)) {
             return false;
         }
@@ -312,7 +332,7 @@ class Http
      */
     public static function headerRemove($name)
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             \header_remove($name);
             return;
         }
@@ -327,6 +347,9 @@ class Http
      */
     public static function responseCode($code) 
     {
+        if (NO_CLI) {
+            return \http_response_code($code);
+        }
         if (isset(HttpCache::$codes[$code])) {
             HttpCache::$status = "HTTP/1.1 $code " . HttpCache::$codes[$code];
             return $code;
@@ -355,7 +378,7 @@ class Http
         $secure = false,
         $HTTPOnly = false
     ) {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             return \setcookie($name, $value, $maxage, $path, $domain, $secure, $HTTPOnly);
         }
 
@@ -389,7 +412,7 @@ class Http
      */
     public static function sessionId($id = null)
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             return $id ? \session_id($id) : \session_id();
         }
         if (static::sessionStarted() && HttpCache::$instance->sessionFile) {
@@ -407,7 +430,7 @@ class Http
      */
     public static function sessionName($name = null)
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             return $name ? \session_name($name) : \session_name();
         }
         $session_name = HttpCache::$sessionName;
@@ -422,11 +445,11 @@ class Http
      *
      * @param string  $path
      *
-     * @return void
+     * @return string
      */
     public static function sessionSavePath($path = null)
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             return $path ? \session_save_path($path) : \session_save_path();
         }
         if ($path && \is_dir($path) && \is_writable($path) && !static::sessionStarted()) {
@@ -454,7 +477,7 @@ class Http
      */
     public static function sessionStart()
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             return \session_start();
         }
 
@@ -503,7 +526,7 @@ class Http
      */
     public static function sessionWriteClose()
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             \session_write_close();
             return true;
         }
@@ -524,7 +547,7 @@ class Http
      */
     public static function end($msg = '')
     {
-        if (PHP_SAPI !== 'cli') {
+        if (NO_CLI) {
             exit($msg);
         }
         if ($msg) {
@@ -681,7 +704,6 @@ class HttpCache
     public static $status               = '';
     public static $header               = array();
     public static $cookie               = array();
-    public static $gzip                 = false;
     public static $sessionPath          = '';
     public static $sessionName          = '';
     public static $sessionGcProbability = 1;
@@ -690,6 +712,15 @@ class HttpCache
     public $sessionStarted = false;
     public $sessionFile = '';
 
+    public static function reset()
+    {
+        self::$status   = 'HTTP/1.1 200 OK';
+        self::$header   = self::$default;
+        self::$cookie   = array();
+        self::$instance->sessionFile = '';
+        self::$instance->sessionStarted = false;
+    }
+
     public static function init()
     {
         if (!self::$sessionName) {
@@ -715,7 +746,11 @@ class HttpCache
         if ($gc_max_life_time = \ini_get('session.gc_maxlifetime')) {
             self::$sessionGcMaxLifeTime = $gc_max_life_time;
         }
+
+        self::$instance = new HttpCache();
     }
 }
 
 HttpCache::init();
+
+define('NO_CLI', \PHP_SAPI !== 'cli');

+ 5 - 5
Protocols/Text.php

@@ -13,7 +13,7 @@
  */
 namespace Workerman\Protocols;
 
-use Workerman\Connection\TcpConnection;
+use Workerman\Connection\ConnectionInterface;
 
 /**
  * Text Protocol.
@@ -24,13 +24,13 @@ class Text
      * Check the integrity of the package.
      *
      * @param string        $buffer
-     * @param TcpConnection $connection
+     * @param ConnectionInterface $connection
      * @return int
      */
-    public static function input($buffer, TcpConnection $connection)
+    public static function input($buffer, ConnectionInterface $connection)
     {
         // Judge whether the package length exceeds the limit.
-        if (\strlen($buffer) >= $connection->maxPackageSize) {
+        if (isset($connection->maxPackageSize) && \strlen($buffer) >= $connection->maxPackageSize) {
             $connection->close();
             return 0;
         }
@@ -67,4 +67,4 @@ class Text
         // Remove "\n"
         return \rtrim($buffer, "\r\n");
     }
-}
+}

+ 13 - 13
Protocols/Websocket.php

@@ -102,7 +102,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                         }
                     } // Close connection.
                     else {
-                        $connection->close("\x88\x02\x27\x10", true);
+                        $connection->close("\x88\x02\x03\xe8", true);
                     }
                     return 0;
                 // Ping package.
@@ -233,7 +233,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
     public static function encode($buffer, ConnectionInterface $connection)
     {
         if (!is_scalar($buffer)) {
-            throw new \Exception("You can't send(" . gettype($buffer) . ") to client, you need to convert it to a string. ");
+            throw new \Exception("You can't send(" . \gettype($buffer) . ") to client, you need to convert it to a string. ");
         }
         $len = \strlen($buffer);
         if (empty($connection->websocketType)) {
@@ -261,7 +261,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             if (\strlen($connection->tmpWebsocketData) > $connection->maxSendBufferSize) {
                 if ($connection->onError) {
                     try {
-                        \call_user_func($connection->onError, $connection, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
+                        \call_user_func($connection->onError, $connection, \WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
                     } catch (\Exception $e) {
                         Worker::log($e);
                         exit(250);
@@ -355,19 +355,19 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             if (\preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
                 $Sec_WebSocket_Key = $match[1];
             } else {
-                $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powerd by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
+                $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powered by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
                     true);
                 $connection->close();
                 return 0;
             }
             // Calculation websocket key.
-            $new_key = \base64_encode(sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
+            $new_key = \base64_encode(\sha1($Sec_WebSocket_Key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
             // Handshake response data.
-            $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n";
-            $handshake_message .= "Upgrade: websocket\r\n";
-            $handshake_message .= "Sec-WebSocket-Version: 13\r\n";
-            $handshake_message .= "Connection: Upgrade\r\n";
-            $handshake_message .= "Sec-WebSocket-Accept: " . $new_key . "\r\n";
+            $handshake_message = "HTTP/1.1 101 Switching Protocols\r\n"
+                                ."Upgrade: websocket\r\n"
+                                ."Sec-WebSocket-Version: 13\r\n"
+                                ."Connection: Upgrade\r\n"
+                                ."Sec-WebSocket-Accept: " . $new_key . "\r\n";
 
             // Websocket data buffer.
             $connection->websocketDataBuffer = '';
@@ -440,7 +440,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             return 0;
         }
         // Bad websocket handshake request.
-        $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powerd by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
+        $connection->send("HTTP/1.1 200 Websocket\r\nServer: workerman/".Worker::VERSION."\r\n\r\n<div style=\"text-align:center\"><h1>Websocket</h1><hr>powered by <a href=\"https://www.workerman.net\">workerman ".Worker::VERSION."</a></div>",
             true);
         $connection->close();
         return 0;
@@ -472,7 +472,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 continue;
             }
             list($key, $value)       = \explode(':', $content, 2);
-            $key                     = \str_replace('-', '_', strtoupper($key));
+            $key                     = \str_replace('-', '_', \strtoupper($key));
             $value                   = \trim($value);
             $_SERVER['HTTP_' . $key] = $value;
             switch ($key) {
@@ -492,7 +492,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
         }
 
         // QUERY_STRING
-        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
+        $_SERVER['QUERY_STRING'] = \parse_url($_SERVER['REQUEST_URI'], \PHP_URL_QUERY);
         if ($_SERVER['QUERY_STRING']) {
             // $GET
             \parse_str($_SERVER['QUERY_STRING'], $_GET);

+ 5 - 5
Protocols/Ws.php

@@ -47,7 +47,7 @@ class Ws
     public static function input($buffer, ConnectionInterface $connection)
     {
         if (empty($connection->handshakeStep)) {
-            Worker::safeEcho("recv data before handshake. Buffer:" . bin2hex($buffer) . "\n");
+            Worker::safeEcho("recv data before handshake. Buffer:" . \bin2hex($buffer) . "\n");
             return false;
         }
         // Recv handshake response
@@ -262,7 +262,7 @@ class Ws
             if (\strlen($connection->tmpWebsocketData) > $connection->maxSendBufferSize) {
                 if ($connection->onError) {
                     try {
-                        \call_user_func($connection->onError, $connection, WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
+                        \call_user_func($connection->onError, $connection, \WORKERMAN_SEND_FAIL, 'send buffer full and drop package');
                     } catch (\Exception $e) {
                         Worker::log($e);
                         exit(250);
@@ -365,7 +365,7 @@ class Ws
         $port = $connection->getRemotePort();
         $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
         // Handshake header.
-        $connection->websocketSecKey = \base64_encode(md5(\mt_rand(), true));
+        $connection->websocketSecKey = \base64_encode(\md5(\mt_rand(), true));
         $user_header = isset($connection->headers) ? $connection->headers :
             (isset($connection->wsHttpHeader) ? $connection->wsHttpHeader : null);
         $user_header_str = '';
@@ -407,7 +407,7 @@ class Ws
         if ($pos) {
             //checking Sec-WebSocket-Accept
             if (\preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
-                if ($match[1] !== \base64_encode(sha1($connection->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
+                if ($match[1] !== \base64_encode(\sha1($connection->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
                     Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . \substr($buffer, 0, $pos) . "\n");
                     $connection->close();
                     return 0;
@@ -466,7 +466,7 @@ class Ws
     }
 
     public static function WSGetServerProtocol($connection) {
-	return (\property_exists($connection, 'WSServerProtocol')?$connection->WSServerProtocol:null);
+	return (\property_exists($connection, 'WSServerProtocol') ? $connection->WSServerProtocol : null);
     }
 
 }

+ 3 - 1
README.md

@@ -7,7 +7,9 @@
 [![License](https://poser.pugx.org/workerman/workerman/license)](https://packagist.org/packages/workerman/workerman)
 
 ## What is it
-Workerman is an asynchronous event driven PHP framework with high performance for easily building fast, scalable network applications. Supports HTTP, Websocket, SSL and other custom protocols. Supports libevent/event extension, [HHVM](https://github.com/facebook/hhvm) , [ReactPHP](https://github.com/reactphp/react).
+Workerman is an asynchronous event-driven PHP framework with high performance to build fast and scalable network applications. 
+Workerman supports HTTP, Websocket, SSL and other custom protocols. 
+Workerman supports libevent/event extension, [HHVM](https://github.com/facebook/hhvm) , [ReactPHP](https://github.com/reactphp/react).
 
 ## Requires
 PHP 5.3 or Higher  

+ 11 - 11
WebServer.php

@@ -53,7 +53,7 @@ class WebServer extends Worker
      */
     public function addRoot($domain, $config)
     {
-        if (is_string($config)) {
+        if (\is_string($config)) {
             $config = array('root' => $config);
         }
         $this->serverRoot[$domain] = $config;
@@ -126,7 +126,7 @@ class WebServer extends Worker
             $this->log("$mime_file mime.type file not fond");
             return;
         }
-        $items = \file($mime_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+        $items = \file($mime_file, \FILE_IGNORE_NEW_LINES | \FILE_SKIP_EMPTY_LINES);
         if (!\is_array($items)) {
             $this->log("get $mime_file mime.type content fail");
             return;
@@ -172,7 +172,7 @@ class WebServer extends Worker
             $workerman_file_extension = 'php';
         }
 
-        $workerman_siteConfig = isset($this->serverRoot[$_SERVER['SERVER_NAME']]) ? $this->serverRoot[$_SERVER['SERVER_NAME']] : current($this->serverRoot);
+        $workerman_siteConfig = isset($this->serverRoot[$_SERVER['SERVER_NAME']]) ? $this->serverRoot[$_SERVER['SERVER_NAME']] : \current($this->serverRoot);
 		$workerman_root_dir = $workerman_siteConfig['root'];
         $workerman_file = "$workerman_root_dir/$workerman_path";
 		if(isset($workerman_siteConfig['additionHeader'])){
@@ -205,7 +205,7 @@ class WebServer extends Worker
 
             // Request php file.
             if ($workerman_file_extension === 'php') {
-                $workerman_cwd = getcwd();
+                $workerman_cwd = \getcwd();
                 \chdir($workerman_root_dir);
                 \ini_set('display_errors', 'off');
                 \ob_start();
@@ -237,7 +237,7 @@ class WebServer extends Worker
         } else {
             // 404
             Http::header("HTTP/1.1 404 Not Found");
-			if(isset($workerman_siteConfig['custom404']) && file_exists($workerman_siteConfig['custom404'])){
+			if(isset($workerman_siteConfig['custom404']) && \file_exists($workerman_siteConfig['custom404'])){
 				$html404 = \file_get_contents($workerman_siteConfig['custom404']);
 			}else{
 				$html404 = '<html><head><title>404 File not found</title></head><body><center><h3>404 Not Found</h3></center></body></html>';
@@ -254,7 +254,7 @@ class WebServer extends Worker
     public static function sendFile($connection, $file_path)
     {
         // Check 304.
-        $info = stat($file_path);
+        $info = \stat($file_path);
         $modified_time = $info ? \date('D, d M Y H:i:s', $info['mtime']) . ' ' . \date_default_timezone_get() : '';
         if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info) {
             // Http 304.
@@ -283,12 +283,12 @@ class WebServer extends Worker
         if (isset(self::$mimeTypeMap[$extension])) {
             $header .= "Content-Type: " . self::$mimeTypeMap[$extension] . "\r\n";
         } else {
-            $header .= "Content-Type: application/octet-stream\r\n";
-            $header .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n";
+            $header .= "Content-Type: application/octet-stream\r\n"
+                    ."Content-Disposition: attachment; filename=\"$file_name\"\r\n";
         }
-        $header .= "Connection: keep-alive\r\n";
-        $header .= $modified_time;
-        $header .= "Content-Length: $file_size\r\n\r\n";
+        $header .= "Connection: keep-alive\r\n"
+                .$modified_time
+                ."Content-Length: $file_size\r\n\r\n";
         $trunk_limit_size = 1024*1024;
         if ($file_size < $trunk_limit_size) {
             return $connection->send($header.\file_get_contents($file_path), true);

+ 174 - 147
Worker.php

@@ -20,7 +20,7 @@ use Workerman\Connection\TcpConnection;
 use Workerman\Connection\UdpConnection;
 use Workerman\Lib\Timer;
 use Workerman\Events\Select;
-use Exception;
+use \Exception;
 
 /**
  * Worker class
@@ -33,7 +33,7 @@ class Worker
      *
      * @var string
      */
-    const VERSION = '3.5.23';
+    const VERSION = '3.5.28';
 
     /**
      * Status starting.
@@ -275,7 +275,7 @@ class Worker
     /**
      * Global event loop.
      *
-     * @var Events\EventInterface
+     * @var EventInterface
      */
     public static $globalEvent = null;
 
@@ -301,6 +301,13 @@ class Worker
     public static $eventLoopClass = '';
 
     /**
+     * Process title
+     *
+     * @var string
+     */
+    public static $processTitle = 'WorkerMan';
+
+    /**
      * The PID of master process.
      *
      * @var int
@@ -434,7 +441,7 @@ class Worker
      *
      * @var string
      */
-    protected static $_OS = OS_TYPE_LINUX;
+    protected static $_OS = \OS_TYPE_LINUX;
 
     /**
      * Processes for windows.
@@ -461,7 +468,7 @@ class Worker
     protected static $_availableEventLoops = array(
         'libevent' => '\Workerman\Events\Libevent',
         'event'    => '\Workerman\Events\Event'
-        // Temporarily removed swoole because it is not stable enough  
+        // Temporarily removed swoole because it is not stable enough
         //'swoole'   => '\Workerman\Events\Swoole'
     );
 
@@ -483,21 +490,21 @@ class Worker
      * @var array
      */
     protected static $_errorType = array(
-        E_ERROR             => 'E_ERROR',             // 1
-        E_WARNING           => 'E_WARNING',           // 2
-        E_PARSE             => 'E_PARSE',             // 4
-        E_NOTICE            => 'E_NOTICE',            // 8
-        E_CORE_ERROR        => 'E_CORE_ERROR',        // 16
-        E_CORE_WARNING      => 'E_CORE_WARNING',      // 32
-        E_COMPILE_ERROR     => 'E_COMPILE_ERROR',     // 64
-        E_COMPILE_WARNING   => 'E_COMPILE_WARNING',   // 128
-        E_USER_ERROR        => 'E_USER_ERROR',        // 256
-        E_USER_WARNING      => 'E_USER_WARNING',      // 512
-        E_USER_NOTICE       => 'E_USER_NOTICE',       // 1024
-        E_STRICT            => 'E_STRICT',            // 2048
-        E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', // 4096
-        E_DEPRECATED        => 'E_DEPRECATED',        // 8192
-        E_USER_DEPRECATED   => 'E_USER_DEPRECATED'   // 16384
+        \E_ERROR             => 'E_ERROR',             // 1
+        \E_WARNING           => 'E_WARNING',           // 2
+        \E_PARSE             => 'E_PARSE',             // 4
+        \E_NOTICE            => 'E_NOTICE',            // 8
+        \E_CORE_ERROR        => 'E_CORE_ERROR',        // 16
+        \E_CORE_WARNING      => 'E_CORE_WARNING',      // 32
+        \E_COMPILE_ERROR     => 'E_COMPILE_ERROR',     // 64
+        \E_COMPILE_WARNING   => 'E_COMPILE_WARNING',   // 128
+        \E_USER_ERROR        => 'E_USER_ERROR',        // 256
+        \E_USER_WARNING      => 'E_USER_WARNING',      // 512
+        \E_USER_NOTICE       => 'E_USER_NOTICE',       // 1024
+        \E_STRICT            => 'E_STRICT',            // 2048
+        \E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR', // 4096
+        \E_DEPRECATED        => 'E_DEPRECATED',        // 8192
+        \E_USER_DEPRECATED   => 'E_USER_DEPRECATED'   // 16384
     );
 
     /**
@@ -549,11 +556,11 @@ class Worker
     protected static function checkSapiEnv()
     {
         // Only for cli.
-        if (PHP_SAPI !== 'cli') {
-            exit("only run in command line mode \n");
+        if (\PHP_SAPI !== 'cli') {
+            exit("Only run in command line mode \n");
         }
-        if (DIRECTORY_SEPARATOR === '\\') {
-            self::$_OS = OS_TYPE_WINDOWS;
+        if (\DIRECTORY_SEPARATOR === '\\') {
+            self::$_OS = \OS_TYPE_WINDOWS;
         }
     }
 
@@ -598,7 +605,7 @@ class Worker
         static::$_statisticsFile                      = \sys_get_temp_dir() . "/$unique_prefix.status";
 
         // Process title.
-        static::setProcessTitle('WorkerMan: master process  start_file=' . static::$_startFile);
+        static::setProcessTitle(static::$processTitle . ': master process  start_file=' . static::$_startFile);
 
         // Init data for worker id.
         static::initId();
@@ -615,7 +622,7 @@ class Worker
     protected static function lock()
     {
         $fd = \fopen(static::$_startFile, 'r');
-        if (!$fd || !flock($fd, LOCK_EX)) {
+        if ($fd && !flock($fd, LOCK_EX)) {
             static::log('Workerman['.static::$_startFile.'] already running.');
             exit;
         }
@@ -629,7 +636,7 @@ class Worker
     protected static function unlock()
     {
         $fd = \fopen(static::$_startFile, 'r');
-        $fd && flock($fd, LOCK_UN);
+        $fd && flock($fd, \LOCK_UN);
     }
 
     /**
@@ -639,7 +646,7 @@ class Worker
      */
     protected static function initWorkers()
     {
-        if (static::$_OS !== OS_TYPE_LINUX) {
+        if (static::$_OS !== \OS_TYPE_LINUX) {
             return;
         }
         foreach (static::$_workers as $worker) {
@@ -679,6 +686,19 @@ class Worker
     }
 
     /**
+     * Reload all worker instances.
+     *
+     * @return void
+     */
+    public static function reloadAllWorkers()
+    {
+        static::init();
+        static::initWorkers();
+        static::displayUI();
+        static::$_status = static::STATUS_RELOADING;
+    }
+
+    /**
      * Get all worker instances.
      *
      * @return array
@@ -697,7 +717,7 @@ class Worker
     {
         return static::$globalEvent;
     }
-    
+
     /**
      * Get main socket resource
      * @return resource
@@ -744,31 +764,31 @@ class Worker
         if (\in_array('-q', $argv)) {
             return;
         }
-        if (static::$_OS !== OS_TYPE_LINUX) {
+        if (static::$_OS !== \OS_TYPE_LINUX) {
             static::safeEcho("----------------------- WORKERMAN -----------------------------\r\n");
-            static::safeEcho('Workerman version:'. static::VERSION. '          PHP version:'. PHP_VERSION. "\r\n");
+            static::safeEcho('Workerman version:'. static::VERSION. '          PHP version:'. \PHP_VERSION. "\r\n");
             static::safeEcho("------------------------ WORKERS -------------------------------\r\n");
             static::safeEcho("worker               listen                              processes status\r\n");
             return;
         }
 
         //show version
-        $line_version = 'Workerman version:' . static::VERSION . \str_pad('PHP version:', 22, ' ', STR_PAD_LEFT) . PHP_VERSION . PHP_EOL;
+        $line_version = 'Workerman version:' . static::VERSION . \str_pad('PHP version:', 22, ' ', \STR_PAD_LEFT) . \PHP_VERSION . \PHP_EOL;
         !\defined('LINE_VERSIOIN_LENGTH') && \define('LINE_VERSIOIN_LENGTH', \strlen($line_version));
         $total_length = static::getSingleLineTotalLength();
-        $line_one = '<n>' . \str_pad('<w> WORKERMAN </w>', $total_length + \strlen('<w></w>'), '-', STR_PAD_BOTH) . '</n>'. PHP_EOL;
-        $line_two = \str_pad('<w> WORKERS </w>' , $total_length  + \strlen('<w></w>'), '-', STR_PAD_BOTH) . PHP_EOL;
+        $line_one = '<n>' . \str_pad('<w> WORKERMAN </w>', $total_length + \strlen('<w></w>'), '-', \STR_PAD_BOTH) . '</n>'. \PHP_EOL;
+        $line_two = \str_pad('<w> WORKERS </w>' , $total_length  + \strlen('<w></w>'), '-', \STR_PAD_BOTH) . \PHP_EOL;
         static::safeEcho($line_one . $line_version . $line_two);
 
         //Show title
         $title = '';
         foreach(static::getUiColumns() as $column_name => $prop){
             $key = '_max' . \ucfirst(\strtolower($column_name)) . 'NameLength';
-            //just keep compatible with listen name 
+            //just keep compatible with listen name
             $column_name === 'socket' && $column_name = 'listen';
             $title.= "<w>{$column_name}</w>"  .  \str_pad('', static::$$key + static::UI_SAFE_LENGTH - \strlen($column_name));
         }
-        $title && static::safeEcho($title . PHP_EOL);
+        $title && static::safeEcho($title . \PHP_EOL);
 
         //Show content
         foreach (static::$_workers as $worker) {
@@ -779,11 +799,11 @@ class Worker
                 $place_holder_length = !empty($matches) ? \strlen(\implode('', $matches[0])) : 0;
                 $content .= \str_pad($worker->{$prop}, static::$$key + static::UI_SAFE_LENGTH + $place_holder_length);
             }
-            $content && static::safeEcho($content . PHP_EOL);
+            $content && static::safeEcho($content . \PHP_EOL);
         }
 
         //Show last line
-        $line_last = \str_pad('', static::getSingleLineTotalLength(), '-') . PHP_EOL;
+        $line_last = \str_pad('', static::getSingleLineTotalLength(), '-') . \PHP_EOL;
         !empty($content) && static::safeEcho($line_last);
 
         if (static::$daemonize) {
@@ -841,7 +861,7 @@ class Worker
      */
     protected static function parseCommand()
     {
-        if (static::$_OS !== OS_TYPE_LINUX) {
+        if (static::$_OS !== \OS_TYPE_LINUX) {
             return;
         }
         global $argv;
@@ -929,19 +949,19 @@ class Worker
                 // Waiting amoment.
                 \usleep(500000);
                 // Display statisitcs data from a disk file.
-                if(is_readable(static::$_statisticsFile)) {
-                    readfile(static::$_statisticsFile);
+                if(\is_readable(static::$_statisticsFile)) {
+                    \readfile(static::$_statisticsFile);
                 }
                 exit(0);
             case 'restart':
             case 'stop':
                 if ($command2 === '-g') {
                     static::$_gracefulStop = true;
-                    $sig = SIGTERM;
+                    $sig = \SIGTERM;
                     static::log("Workerman[$start_file] is gracefully stopping ...");
                 } else {
                     static::$_gracefulStop = false;
-                    $sig = SIGINT;
+                    $sig = \SIGINT;
                     static::log("Workerman[$start_file] is stopping ...");
                 }
                 // Send stop signal to master process.
@@ -975,9 +995,9 @@ class Worker
                 break;
             case 'reload':
                 if($command2 === '-g'){
-                    $sig = SIGQUIT;
+                    $sig = \SIGQUIT;
                 }else{
-                    $sig = SIGUSR1;
+                    $sig = \SIGUSR1;
                 }
                 \posix_kill($master_pid, $sig);
                 exit;
@@ -997,16 +1017,16 @@ class Worker
     protected static function formatStatusData()
     {
         static $total_request_cache = array();
-        if (!is_readable(static::$_statisticsFile)) {
+        if (!\is_readable(static::$_statisticsFile)) {
             return '';
         }
-        $info = file(static::$_statisticsFile, FILE_IGNORE_NEW_LINES);
+        $info = \file(static::$_statisticsFile, \FILE_IGNORE_NEW_LINES);
         if (!$info) {
             return '';
         }
         $status_str = '';
         $current_total_request = array();
-        $worker_info = \json_decode($info[0], true);
+        $worker_info = \unserialize($info[0]);
         \ksort($worker_info, SORT_NUMERIC);
         unset($info[0]);
         $data_waiting_sort = array();
@@ -1031,7 +1051,7 @@ class Worker
                 $pid = $pid_math[0];
                 $data_waiting_sort[$pid] = $value;
                 if(\preg_match('/^\S+?\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?(\S+?)\s+?/', $value, $match)) {
-                    $total_memory += \intval(str_ireplace('M','',$match[1]));
+                    $total_memory += \intval(\str_ireplace('M','',$match[1]));
                     $maxLen1 = \max($maxLen1,\strlen($match[2]));
                     $maxLen2 = \max($maxLen2,\strlen($match[3]));
                     $total_connections += \intval($match[4]);
@@ -1079,23 +1099,24 @@ class Worker
      */
     protected static function installSignal()
     {
-        if (static::$_OS !== OS_TYPE_LINUX) {
+        if (static::$_OS !== \OS_TYPE_LINUX) {
             return;
         }
+        $signalHandler = '\Workerman\Worker::signalHandler';
         // stop
-        \pcntl_signal(SIGINT, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGINT, $signalHandler, false);
         // graceful stop
-        \pcntl_signal(SIGTERM, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGTERM, $signalHandler, false);
         // reload
-        \pcntl_signal(SIGUSR1, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGUSR1, $signalHandler, false);
         // graceful reload
-        \pcntl_signal(SIGQUIT, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGQUIT, $signalHandler, false);
         // status
-        \pcntl_signal(SIGUSR2, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGUSR2, $signalHandler, false);
         // connection status
-        \pcntl_signal(SIGIO, array('\Workerman\Worker', 'signalHandler'), false);
+        \pcntl_signal(\SIGIO, $signalHandler, false);
         // ignore
-        \pcntl_signal(SIGPIPE, SIG_IGN, false);
+        \pcntl_signal(\SIGPIPE, \SIG_IGN, false);
     }
 
     /**
@@ -1105,33 +1126,34 @@ class Worker
      */
     protected static function reinstallSignal()
     {
-        if (static::$_OS !== OS_TYPE_LINUX) {
+        if (static::$_OS !== \OS_TYPE_LINUX) {
             return;
         }
+        $signalHandler = '\Workerman\Worker::signalHandler';
         // uninstall stop signal handler
-        \pcntl_signal(SIGINT, SIG_IGN, false);
+        \pcntl_signal(\SIGINT, \SIG_IGN, false);
         // uninstall graceful stop signal handler
-        \pcntl_signal(SIGTERM, SIG_IGN, false);
+        \pcntl_signal(\SIGTERM, \SIG_IGN, false);
         // uninstall reload signal handler
-        \pcntl_signal(SIGUSR1, SIG_IGN, false);
+        \pcntl_signal(\SIGUSR1, \SIG_IGN, false);
         // uninstall graceful reload signal handler
-        \pcntl_signal(SIGQUIT, SIG_IGN, false);
+        \pcntl_signal(\SIGQUIT, \SIG_IGN, false);
         // uninstall status signal handler
-        \pcntl_signal(SIGUSR2, SIG_IGN, false);
+        \pcntl_signal(\SIGUSR2, \SIG_IGN, false);
         // uninstall connections status signal handler
-        \pcntl_signal(SIGIO, SIG_IGN, false);
+        \pcntl_signal(\SIGIO, \SIG_IGN, false);
         // reinstall stop signal handler
-        static::$globalEvent->add(SIGINT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGINT, EventInterface::EV_SIGNAL, $signalHandler);
         // reinstall graceful stop signal handler
-        static::$globalEvent->add(SIGTERM, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGTERM, EventInterface::EV_SIGNAL, $signalHandler);
         // reinstall reload signal handler
-        static::$globalEvent->add(SIGUSR1, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGUSR1, EventInterface::EV_SIGNAL, $signalHandler);
         // reinstall graceful reload signal handler
-        static::$globalEvent->add(SIGQUIT, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGQUIT, EventInterface::EV_SIGNAL, $signalHandler);
         // reinstall status signal handler
-        static::$globalEvent->add(SIGUSR2, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGUSR2, EventInterface::EV_SIGNAL, $signalHandler);
         // reinstall connection status signal handler
-        static::$globalEvent->add(SIGIO, EventInterface::EV_SIGNAL, array('\Workerman\Worker', 'signalHandler'));
+        static::$globalEvent->add(\SIGIO, EventInterface::EV_SIGNAL, $signalHandler);
     }
 
     /**
@@ -1143,19 +1165,19 @@ class Worker
     {
         switch ($signal) {
             // Stop.
-            case SIGINT:
+            case \SIGINT:
                 static::$_gracefulStop = false;
                 static::stopAll();
                 break;
             // Graceful stop.
-            case SIGTERM:
+            case \SIGTERM:
                 static::$_gracefulStop = true;
                 static::stopAll();
                 break;
             // Reload.
-            case SIGQUIT:
-            case SIGUSR1:
-                if($signal === SIGQUIT){
+            case \SIGQUIT:
+            case \SIGUSR1:
+                if($signal === \SIGQUIT){
                     static::$_gracefulStop = true;
                 }else{
                     static::$_gracefulStop = false;
@@ -1164,11 +1186,11 @@ class Worker
                 static::reload();
                 break;
             // Show status.
-            case SIGUSR2:
+            case \SIGUSR2:
                 static::writeStatisticsToStatusFile();
                 break;
             // Show connection status.
-            case SIGIO:
+            case \SIGIO:
                 static::writeConnectionsStatisticsToStatusFile();
                 break;
         }
@@ -1181,23 +1203,23 @@ class Worker
      */
     protected static function daemonize()
     {
-        if (!static::$daemonize || static::$_OS !== OS_TYPE_LINUX) {
+        if (!static::$daemonize || static::$_OS !== \OS_TYPE_LINUX) {
             return;
         }
         \umask(0);
         $pid = \pcntl_fork();
         if (-1 === $pid) {
-            throw new Exception('fork fail');
+            throw new Exception('Fork fail');
         } elseif ($pid > 0) {
             exit(0);
         }
         if (-1 === \posix_setsid()) {
-            throw new Exception("setsid fail");
+            throw new Exception("Setsid fail");
         }
         // Fork again avoid SVR4 system regain the control of terminal.
         $pid = \pcntl_fork();
         if (-1 === $pid) {
-            throw new Exception("fork fail");
+            throw new Exception("Fork fail");
         } elseif (0 !== $pid) {
             exit(0);
         }
@@ -1210,7 +1232,7 @@ class Worker
      */
     public static function resetStd()
     {
-        if (!static::$daemonize || static::$_OS !== OS_TYPE_LINUX) {
+        if (!static::$daemonize || static::$_OS !== \OS_TYPE_LINUX) {
             return;
         }
         global $STDOUT, $STDERR;
@@ -1220,17 +1242,18 @@ class Worker
             \set_error_handler(function(){});
             \fclose($STDOUT);
             \fclose($STDERR);
-            \fclose(STDOUT);
-            \fclose(STDERR);
+            \fclose(\STDOUT);
+            \fclose(\STDERR);
             $STDOUT = \fopen(static::$stdoutFile, "a");
             $STDERR = \fopen(static::$stdoutFile, "a");
             // change output stream
             static::$_outputStream = null;
             static::outputStream($STDOUT);
             \restore_error_handler();
-        } else {
-            throw new Exception('can not open stdoutFile ' . static::$stdoutFile);
+            return;
         }
+
+        throw new Exception('Can not open stdoutFile ' . static::$stdoutFile);
     }
 
     /**
@@ -1240,7 +1263,7 @@ class Worker
      */
     protected static function saveMasterPid()
     {
-        if (static::$_OS !== OS_TYPE_LINUX) {
+        if (static::$_OS !== \OS_TYPE_LINUX) {
             return;
         }
 
@@ -1264,7 +1287,7 @@ class Worker
         if (!\class_exists('\Swoole\Event', false)) {
             unset(static::$_availableEventLoops['swoole']);
         }
-        
+
         $loop_name = '';
         foreach (static::$_availableEventLoops as $name=>$class) {
             if (\extension_loaded($name)) {
@@ -1318,7 +1341,7 @@ class Worker
      */
     protected static function forkWorkers()
     {
-        if (static::$_OS === OS_TYPE_LINUX) {
+        if (static::$_OS === \OS_TYPE_LINUX) {
             static::forkWorkersForLinux();
         } else {
             static::forkWorkersForWindows();
@@ -1512,7 +1535,7 @@ class Worker
                 }
             }
             Timer::delAll();
-            static::setProcessTitle('WorkerMan: worker process  ' . $worker->name . ' ' . $worker->getSocketName());
+            static::setProcessTitle(self::$processTitle . ': worker process  ' . $worker->name . ' ' . $worker->getSocketName());
             $worker->setUserAndGroup();
             $worker->id = $id;
             $worker->run();
@@ -1597,7 +1620,7 @@ class Worker
      */
     protected static function monitorWorkers()
     {
-        if (static::$_OS === OS_TYPE_LINUX) {
+        if (static::$_OS === \OS_TYPE_LINUX) {
             static::monitorWorkersForLinux();
         } else {
             static::monitorWorkersForWindows();
@@ -1617,7 +1640,7 @@ class Worker
             \pcntl_signal_dispatch();
             // Suspends execution of the current process until a child has exited, or until a signal is delivered
             $status = 0;
-            $pid    = \pcntl_wait($status, WUNTRACED);
+            $pid    = \pcntl_wait($status, \WUNTRACED);
             // Calls signal handlers for pending signals again.
             \pcntl_signal_dispatch();
             // If a child has already exited.
@@ -1635,7 +1658,7 @@ class Worker
                         if (!isset(static::$_globalStatistics['worker_exit_info'][$worker_id][$status])) {
                             static::$_globalStatistics['worker_exit_info'][$worker_id][$status] = 0;
                         }
-                        static::$_globalStatistics['worker_exit_info'][$worker_id][$status]++;
+                        ++static::$_globalStatistics['worker_exit_info'][$worker_id][$status];
 
                         // Clear process data.
                         unset(static::$_pidMap[$worker_id][$pid]);
@@ -1728,9 +1751,9 @@ class Worker
             }
 
             if (static::$_gracefulStop) {
-                $sig = SIGQUIT;
+                $sig = \SIGQUIT;
             } else {
-                $sig = SIGUSR1;
+                $sig = \SIGUSR1;
             }
 
             // Send reload signal to all child processes.
@@ -1765,7 +1788,7 @@ class Worker
             \posix_kill($one_worker_pid, $sig);
             // If the process does not exit after static::KILL_WORKER_TIMER_TIME seconds try to kill it.
             if(!static::$_gracefulStop){
-                Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($one_worker_pid, SIGKILL), false);
+                Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($one_worker_pid, \SIGKILL), false);
             }
         } // For child processes.
         else {
@@ -1804,14 +1827,14 @@ class Worker
             $worker_pid_array = static::getAllWorkerPids();
             // Send stop signal to all child processes.
             if (static::$_gracefulStop) {
-                $sig = SIGTERM;
+                $sig = \SIGTERM;
             } else {
-                $sig = SIGINT;
+                $sig = \SIGINT;
             }
             foreach ($worker_pid_array as $worker_pid) {
                 \posix_kill($worker_pid, $sig);
                 if(!static::$_gracefulStop){
-                    Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($worker_pid, SIGKILL), false);
+                    Timer::add(static::KILL_WORKER_TIMER_TIME, '\posix_kill', array($worker_pid, \SIGKILL), false);
                 }
             }
             Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning");
@@ -1890,49 +1913,49 @@ class Worker
                 }
             }
 
-            \file_put_contents(static::$_statisticsFile, \json_encode($all_worker_info)."\n", FILE_APPEND);
-            $loadavg = \function_exists('sys_getloadavg') ? \array_map('round', sys_getloadavg(), array(2)) : array('-', '-', '-');
+            \file_put_contents(static::$_statisticsFile, \serialize($all_worker_info)."\n", \FILE_APPEND);
+            $loadavg = \function_exists('sys_getloadavg') ? \array_map('round', \sys_getloadavg(), array(2)) : array('-', '-', '-');
             \file_put_contents(static::$_statisticsFile,
-                "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", FILE_APPEND);
+                "----------------------------------------------GLOBAL STATUS----------------------------------------------------\n", \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
-                'Workerman version:' . static::VERSION . "          PHP version:" . PHP_VERSION . "\n", FILE_APPEND);
+                'Workerman version:' . static::VERSION . "          PHP version:" . \PHP_VERSION . "\n", \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile, 'start time:' . \date('Y-m-d H:i:s',
                     static::$_globalStatistics['start_timestamp']) . '   run ' . \floor((\time() - static::$_globalStatistics['start_timestamp']) / (24 * 60 * 60)) . ' days ' . \floor(((\time() - static::$_globalStatistics['start_timestamp']) % (24 * 60 * 60)) / (60 * 60)) . " hours   \n",
                 FILE_APPEND);
             $load_str = 'load average: ' . \implode(", ", $loadavg);
             \file_put_contents(static::$_statisticsFile,
-                \str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", FILE_APPEND);
+                \str_pad($load_str, 33) . 'event-loop:' . static::getEventLoopName() . "\n", \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
                 \count(static::$_pidMap) . ' workers       ' . \count(static::getAllWorkerPids()) . " processes\n",
-                FILE_APPEND);
+                \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
-                \str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status      exit_count\n", FILE_APPEND);
+                \str_pad('worker_name', static::$_maxWorkerNameLength) . " exit_status      exit_count\n", \FILE_APPEND);
             foreach (static::$_pidMap as $worker_id => $worker_pid_array) {
                 $worker = static::$_workers[$worker_id];
                 if (isset(static::$_globalStatistics['worker_exit_info'][$worker_id])) {
                     foreach (static::$_globalStatistics['worker_exit_info'][$worker_id] as $worker_exit_status => $worker_exit_count) {
                         \file_put_contents(static::$_statisticsFile,
                             \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad($worker_exit_status,
-                                16) . " $worker_exit_count\n", FILE_APPEND);
+                                16) . " $worker_exit_count\n", \FILE_APPEND);
                     }
                 } else {
                     \file_put_contents(static::$_statisticsFile,
                         \str_pad($worker->name, static::$_maxWorkerNameLength) . " " . \str_pad(0, 16) . " 0\n",
-                        FILE_APPEND);
+                        \FILE_APPEND);
                 }
             }
             \file_put_contents(static::$_statisticsFile,
                 "----------------------------------------------PROCESS STATUS---------------------------------------------------\n",
-                FILE_APPEND);
+                \FILE_APPEND);
             \file_put_contents(static::$_statisticsFile,
                 "pid\tmemory  " . \str_pad('listening', static::$_maxSocketNameLength) . " " . \str_pad('worker_name',
                     static::$_maxWorkerNameLength) . " connections " . \str_pad('send_fail', 9) . " "
-                . \str_pad('timers', 8) . \str_pad('total_request', 13) ." qps    status\n", FILE_APPEND);
+                . \str_pad('timers', 8) . \str_pad('total_request', 13) ." qps    status\n", \FILE_APPEND);
 
             \chmod(static::$_statisticsFile, 0722);
 
             foreach (static::getAllWorkerPids() as $worker_pid) {
-                \posix_kill($worker_pid, SIGUSR2);
+                \posix_kill($worker_pid, \SIGUSR2);
             }
             return;
         }
@@ -1943,13 +1966,13 @@ class Worker
         $worker            = current(static::$_workers);
         $worker_status_str = \posix_getpid() . "\t" . \str_pad(round(memory_get_usage(true) / (1024 * 1024), 2) . "M", 7)
             . " " . \str_pad($worker->getSocketName(), static::$_maxSocketNameLength) . " "
-            . str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
+            . \str_pad(($worker->name === $worker->getSocketName() ? 'none' : $worker->name), static::$_maxWorkerNameLength)
             . " ";
         $worker_status_str .= \str_pad(ConnectionInterface::$statistics['connection_count'], 11)
             . " " .  \str_pad(ConnectionInterface::$statistics['send_fail'], 9)
             . " " . \str_pad(static::$globalEvent->getTimerCount(), 7)
             . " " . \str_pad(ConnectionInterface::$statistics['total_request'], 13) . "\n";
-        \file_put_contents(static::$_statisticsFile, $worker_status_str, FILE_APPEND);
+        \file_put_contents(static::$_statisticsFile, $worker_status_str, \FILE_APPEND);
     }
 
     /**
@@ -1961,11 +1984,11 @@ class Worker
     {
         // For master process.
         if (static::$_masterPid === \posix_getpid()) {
-            \file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", FILE_APPEND);
-            \file_put_contents(static::$_statisticsFile, "PID      Worker          CID       Trans   Protocol        ipv4   ipv6   Recv-Q       Send-Q       Bytes-R      Bytes-W       Status         Local Address          Foreign Address\n", FILE_APPEND);
+            \file_put_contents(static::$_statisticsFile, "--------------------------------------------------------------------- WORKERMAN CONNECTION STATUS --------------------------------------------------------------------------------\n", \FILE_APPEND);
+            \file_put_contents(static::$_statisticsFile, "PID      Worker          CID       Trans   Protocol        ipv4   ipv6   Recv-Q       Send-Q       Bytes-R      Bytes-W       Status         Local Address          Foreign Address\n", \FILE_APPEND);
             \chmod(static::$_statisticsFile, 0722);
             foreach (static::getAllWorkerPids() as $worker_pid) {
-                \posix_kill($worker_pid, SIGIO);
+                \posix_kill($worker_pid, \SIGIO);
             }
             return;
         }
@@ -2026,7 +2049,7 @@ class Worker
                 . \str_pad($state, 14) . ' ' . \str_pad($local_address, 22) . ' ' . \str_pad($remote_address, 22) ."\n";
         }
         if ($str) {
-            \file_put_contents(static::$_statisticsFile, $str, FILE_APPEND);
+            \file_put_contents(static::$_statisticsFile, $str, \FILE_APPEND);
         }
     }
 
@@ -2038,13 +2061,13 @@ class Worker
     public static function checkErrors()
     {
         if (static::STATUS_SHUTDOWN !== static::$_status) {
-            $error_msg = static::$_OS === OS_TYPE_LINUX ? 'Worker['. \posix_getpid() .'] process terminated' : 'Worker process terminated';
+            $error_msg = static::$_OS === \OS_TYPE_LINUX ? 'Worker['. \posix_getpid() .'] process terminated' : 'Worker process terminated';
             $errors    = error_get_last();
-            if ($errors && ($errors['type'] === E_ERROR ||
-                    $errors['type'] === E_PARSE ||
-                    $errors['type'] === E_CORE_ERROR ||
-                    $errors['type'] === E_COMPILE_ERROR ||
-                    $errors['type'] === E_RECOVERABLE_ERROR)
+            if ($errors && ($errors['type'] === \E_ERROR ||
+                    $errors['type'] === \E_PARSE ||
+                    $errors['type'] === \E_CORE_ERROR ||
+                    $errors['type'] === \E_COMPILE_ERROR ||
+                    $errors['type'] === \E_RECOVERABLE_ERROR)
             ) {
                 $error_msg .= ' with ERROR: ' . static::getErrorType($errors['type']) . " \"{$errors['message']} in {$errors['file']} on line {$errors['line']}\"";
             }
@@ -2080,7 +2103,7 @@ class Worker
             static::safeEcho($msg);
         }
         \file_put_contents((string)static::$logFile, \date('Y-m-d H:i:s') . ' ' . 'pid:'
-            . (static::$_OS === OS_TYPE_LINUX ? \posix_getpid() : 1) . ' ' . $msg, FILE_APPEND | LOCK_EX);
+            . (static::$_OS === \OS_TYPE_LINUX ? \posix_getpid() : 1) . ' ' . $msg, \FILE_APPEND | \LOCK_EX);
     }
 
     /**
@@ -2120,18 +2143,21 @@ class Worker
     private static function outputStream($stream = null)
     {
         if (!$stream) {
-            $stream = static::$_outputStream ? static::$_outputStream : STDOUT;
+            $stream = static::$_outputStream ? static::$_outputStream : \STDOUT;
         }
         if (!$stream || !\is_resource($stream) || 'stream' !== \get_resource_type($stream)) {
             return false;
         }
         $stat = \fstat($stream);
+        if (!$stat) {
+            return false;
+        }
         if (($stat['mode'] & 0170000) === 0100000) {
             // file
             static::$_outputDecorated = false;
         } else {
             static::$_outputDecorated =
-                static::$_OS === OS_TYPE_LINUX &&
+                static::$_OS === \OS_TYPE_LINUX &&
                 \function_exists('posix_isatty') &&
                 \posix_isatty($stream);
         }
@@ -2152,26 +2178,27 @@ class Worker
         static::$_pidMap[$this->workerId]  = array();
 
         // Get autoload root path.
-        $backtrace                = \debug_backtrace();
+        $backtrace               = \debug_backtrace();
         $this->_autoloadRootPath = \dirname($backtrace[0]['file']);
-
-        if (static::$_OS === OS_TYPE_LINUX && version_compare(PHP_VERSION,'7.0.0', 'ge')) {
-            $php_uname = strtolower(php_uname('s'));
-            // If not Mac OS then turn reusePort on.
-            if ($php_uname !== 'darwin') {
-                $this->reusePort = true;
-            }
-        }
+        Autoloader::setRootPath($this->_autoloadRootPath);
 
         // Context for socket.
         if ($socket_name) {
             $this->_socketName = $socket_name;
-            $this->_localSocket = $this->parseSocketAddress();
             if (!isset($context_option['socket']['backlog'])) {
                 $context_option['socket']['backlog'] = static::DEFAULT_BACKLOG;
             }
             $this->_context = \stream_context_create($context_option);
         }
+
+        // Turn reusePort on.
+        if (static::$_OS === \OS_TYPE_LINUX  // if linux
+            && \version_compare(\PHP_VERSION,'7.0.0', 'ge') // if php >= 7.0.0
+            && \strtolower(\php_uname('s')) !== 'darwin' // if not Mac OS
+            && $this->transport !== 'unix') { // if not unix socket
+
+            $this->reusePort = true;
+        }
     }
 
 
@@ -2191,10 +2218,10 @@ class Worker
 
         if (!$this->_mainSocket) {
 
-            $local_socket = !empty($this->_localSocket) ? $this->_localSocket : $this->parseSocketAddress();
+            $local_socket = $this->parseSocketAddress();
 
             // Flag.
-            $flags = $this->transport === 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN;
+            $flags = $this->transport === 'udp' ? \STREAM_SERVER_BIND : \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN;
             $errno = 0;
             $errmsg = '';
             // SO_REUSEPORT.
@@ -2213,10 +2240,10 @@ class Worker
             } elseif ($this->transport === 'unix') {
                 $socket_file = \substr($local_socket, 7);
                 if ($this->user) {
-                    chown($socket_file, $this->user);
+                    \chown($socket_file, $this->user);
                 }
                 if ($this->group) {
-                    chgrp($socket_file, $this->group);
+                    \chgrp($socket_file, $this->group);
                 }
             }
 
@@ -2224,8 +2251,8 @@ class Worker
             if (\function_exists('socket_import_stream') && static::$_builtinTransports[$this->transport] === 'tcp') {
                 \set_error_handler(function(){});
                 $socket = \socket_import_stream($this->_mainSocket);
-                \socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1);
-                \socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1);
+                \socket_set_option($socket, \SOL_SOCKET, \SO_KEEPALIVE, 1);
+                \socket_set_option($socket, \SOL_TCP, \TCP_NODELAY, 1);
                 \restore_error_handler();
             }
 
@@ -2274,7 +2301,7 @@ class Worker
             }
 
             if (!isset(static::$_builtinTransports[$this->transport])) {
-                throw new \Exception('Bad worker->transport ' . \var_export($this->transport, true));
+                throw new Exception('Bad worker->transport ' . \var_export($this->transport, true));
             }
         } else {
             $this->transport = $scheme;
@@ -2321,7 +2348,7 @@ class Worker
      */
     public function getSocketName()
     {
-        return $this->_socketName ? lcfirst($this->_socketName) : 'none';
+        return $this->_socketName ? \lcfirst($this->_socketName) : 'none';
     }
 
     /**
@@ -2359,7 +2386,7 @@ class Worker
         }
 
         \restore_error_handler();
-        
+
         // Try to emit onWorkerStart callback.
         if ($this->onWorkerStart) {
             try {
@@ -2422,7 +2449,7 @@ class Worker
     {
         // Accept a connection on server socket.
         \set_error_handler(function(){});
-        $new_socket = stream_socket_accept($socket, 0, $remote_address);
+        $new_socket = \stream_socket_accept($socket, 0, $remote_address);
         \restore_error_handler();
 
         // Thundering herd.
@@ -2500,7 +2527,7 @@ class Worker
                 }else{
                     \call_user_func($this->onMessage, $connection, $recv_buffer);
                 }
-                ConnectionInterface::$statistics['total_request']++;
+                ++ConnectionInterface::$statistics['total_request'];
             } catch (\Exception $e) {
                 static::log($e);
                 exit(250);