Ver código fonte

English comments

walkor 9 anos atrás
pai
commit
162337e56a

+ 11 - 16
Autoloader.php

@@ -14,56 +14,52 @@
 namespace Workerman;
 
 /**
- * 自动加载类
- * @author walkor<walkor@workerman.net>
+ * Autoload.
  */
 class Autoloader
 {
-    // 应用的初始化目录,作为加载类文件的参考目录
-    protected static $_appInitPath = '';
+    /**
+     * Autoload root path.
+     * @var string
+     */
+    protected static $_autoloadRootPath = '';
     
     /**
-     * 设置应用初始化目录
+     * Set autoload root path.
      * @param string $root_path
      * @return void
      */
     public static function setRootPath($root_path)
     {
-          self::$_appInitPath = $root_path;
+          self::$_autoloadRootPath = $root_path;
     }
 
     /**
-     * 根据命名空间加载文件
+     * Load files by namespace.
      * @param string $name
      * @return boolean
      */
     public static function loadByNamespace($name)
     {
-        // 相对路径
         $class_path = str_replace('\\', DIRECTORY_SEPARATOR ,$name);
-        // 如果是Workerman命名空间,则在当前目录寻找类文件
         if(strpos($name, 'Workerman\\') === 0)
         {
             $class_file = __DIR__.substr($class_path, strlen('Workerman')).'.php';
         }
         else 
         {
-            // 先尝试在应用目录寻找文件
-            if(self::$_appInitPath)
+            if(self::$_autoloadRootPath)
             {
-                $class_file = self::$_appInitPath . 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";
             }
         }
        
-        // 找到文件
         if(is_file($class_file))
         {
-            // 加载
             require_once($class_file);
             if(class_exists($name, false))
             {
@@ -73,5 +69,4 @@ class Autoloader
         return false;
     }
 }
-// 设置类自动加载回调函数
 spl_autoload_register('\Workerman\Autoloader::loadByNamespace');

+ 18 - 22
Connection/AsyncTcpConnection.php

@@ -18,25 +18,25 @@ use Workerman\Worker;
 use \Exception;
 
 /**
- * 异步tcp连接类 
+ * AsyncTcpConnection.
  */
 class AsyncTcpConnection extends TcpConnection
 {
     
     /**
-     * 当连接成功时,如果设置了连接成功回调,则执行
+     * Emitted when socket connection is successfully established. 
      * @var callback
      */
     public $onConnect = null;
     
     /**
-     * 连接状态 连接中
+     * Status.
      * @var int
      */
     protected $_status = self::STATUS_CONNECTING;
     
     /**
-     * 构造函数,创建连接
+     * Construct.
      * @param resource $socket
      * @param EventInterface $event
      */
@@ -45,7 +45,7 @@ class AsyncTcpConnection extends TcpConnection
         list($scheme, $address) = explode(':', $remote_address, 2);
         if($scheme != 'tcp')
         {
-            // 判断协议类是否存在
+            // Get application layer protocol.
             $scheme = ucfirst($scheme);
             $this->protocol = '\\Protocols\\'.$scheme;
             if(!class_exists($this->protocol))
@@ -59,28 +59,28 @@ class AsyncTcpConnection extends TcpConnection
         }
         $this->_remoteAddress = substr($address, 2);
         $this->id = self::$_idRecorder++;
-        // 统计数据
+        // For statistics.
         self::$statistics['connection_count']++;
         $this->maxSendBufferSize = self::$defaultMaxSendBufferSize;
     }
     
     public function connect()
     {
-        // 创建异步连接
+        // Open socket connection asynchronously.
         $this->_socket = stream_socket_client("tcp://{$this->_remoteAddress}", $errno, $errstr, 0, STREAM_CLIENT_ASYNC_CONNECT);
-        // 如果失败尝试触发失败回调(如果有回调的话)
+        // If failed attempt to emit onError callback.
         if(!$this->_socket)
         {
             $this->_status = self::STATUS_CLOSED;
             $this->emitError(WORKERMAN_CONNECT_FAIL, $errstr);
             return;
         }
-        // 监听连接可写事件(可写意味着连接已经建立或者已经出错)
+        // Add socket to global event loop waiting connection is successfully established or faild. 
         Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'checkConnection'));
     }
     
     /**
-     * 尝试触发失败回调
+     * Try to emit onError callback.
      * @param int $code
      * @param string $msg
      * @return void
@@ -102,31 +102,29 @@ class AsyncTcpConnection extends TcpConnection
     }
     
     /**
-     * 检查连接状态,连接成功还是失败
+     * Check connection is successfully established or faild.
      * @param resource $socket
      * @return void
      */
     public function checkConnection($socket)
     {
-        // 需要判断两次连接是否已经断开
+        // Need call foef twice.
         if(!feof($this->_socket) && !feof($this->_socket) && is_resource($this->_socket))
         {
-            // 删除连接可写监听
+            // Remove write listener.
             Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
-            // 设置非阻塞
+            // Nonblocking.
             stream_set_blocking($this->_socket, 0);
-            // 监听可读事件
+            // Register a listener waiting read event.
             Worker::$globalEvent->add($this->_socket, EventInterface::EV_READ, array($this, 'baseRead'));
-            // 如果发送缓冲区有数据则执行发送
+            // There are some data waiting to send.
             if($this->_sendBuffer)
             {
                 Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
             }
-            // 标记状态为连接已经建立
             $this->_status = self::STATUS_ESTABLISH;
-            // 获得远端实际ip端口
             $this->_remoteAddress = stream_socket_get_name($this->_socket, true);
-            // 如果有设置onConnect回调,则执行
+            // Try to emit onConnect callback.
             if($this->onConnect)
             {
                 try
@@ -142,11 +140,9 @@ class AsyncTcpConnection extends TcpConnection
         }
         else
         {
-            // 连接未建立成功
+            // Connection failed.
             $this->emitError(WORKERMAN_CONNECT_FAIL, 'connect fail');
-            // 触发onClsoe
             $this->destroy();
-            // 清理onConnect回调
             $this->onConnect = null;
         }
     }

+ 10 - 10
Connection/ConnectionInterface.php

@@ -14,12 +14,12 @@
 namespace Workerman\Connection;
 
 /**
- * connection类的接口 
+ * ConnectionInterface.
  */
 abstract class  ConnectionInterface
 {
     /**
-     * status命令的统计数据
+     * Statistics for status command.
      * @var array
      */
     public static $statistics = array(
@@ -30,45 +30,45 @@ abstract class  ConnectionInterface
     );
     
     /**
-     * 当收到数据时,如果有设置$onMessage回调,则执行
+     * Emitted when data is received. 
      * @var callback
      */
     public $onMessage = null;
     
     /**
-     * 当连接关闭时,如果设置了$onClose回调,则执行
+     * Emitted when the other end of the socket sends a FIN packet.
      * @var callback
      */
     public $onClose = null;
     
     /**
-     * 当出现错误时,如果设置了$onError回调,则执行
+     * Emitted when an error occurs with connection. 
      * @var callback
      */
     public $onError = null;
     
     /**
-     * 发送数据给对端
+     * Sends data on the connection.
      * @param string $send_buffer
      * @return void|boolean
      */
     abstract public function send($send_buffer);
     
     /**
-     * 获得远端ip
+     * Get remote IP.
      * @return string
      */
     abstract public function getRemoteIp();
     
     /**
-     * 获得远端端口
+     * Get remote port.
      * @return int
      */
     abstract public function getRemotePort();
 
     /**
-     * 关闭连接,为了保持接口一致,udp保留了此方法,当是udp时调用此方法无任何作用
-     * @void
+     * Close connection.
+     * @return void
      */
     abstract public function close($data = null);
 }

+ 74 - 99
Connection/TcpConnection.php

@@ -18,178 +18,169 @@ use Workerman\Worker;
 use \Exception;
 
 /**
- * Tcp连接类 
+ * TcpConnection.
  */
 class TcpConnection extends ConnectionInterface
 {
     /**
-     * 当数据可读时,从socket缓冲区读取多少字节数据
+     * Read buffer size.
      * @var int
      */
     const READ_BUFFER_SIZE = 65535;
 
     /**
-     * 连接状态 连接中
+     * Status connecting.
      * @var int
      */
     const STATUS_CONNECTING = 1;
     
     /**
-     * 连接状态 已经建立连接
+     * Status connection established.
      * @var int
      */
     const STATUS_ESTABLISH = 2;
 
     /**
-     * 连接状态 连接关闭中,标识调用了close方法,但是发送缓冲区中任然有数据
-     * 等待发送缓冲区的数据发送完毕(写入到socket写缓冲区)后执行关闭
+     * Status closing.
      * @var int
      */
     const STATUS_CLOSING = 4;
     
     /**
-     * 连接状态 已经关闭
+     * Status closed.
      * @var int
      */
     const STATUS_CLOSED = 8;
     
     /**
-     * 当对端发来数据时,如果设置了$onMessage回调,则执行
+     * Emitted when data is received. 
      * @var callback
      */
     public $onMessage = null;
     
     /**
-     * 当连接关闭时,如果设置了$onClose回调,则执行
+     * Emitted when the other end of the socket sends a FIN packet.
      * @var callback
      */
     public $onClose = null;
     
     /**
-     * 当出现错误是,如果设置了$onError回调,则执行
+     * Emitted when an error occurs with connection. 
      * @var callback
      */
     public $onError = null;
     
     /**
-     * 当发送缓冲区满时,如果设置了$onBufferFull回调,则执行
+     * Emitted when the send buffer becomes full. 
      * @var callback
      */
     public $onBufferFull = null;
     
     /**
-     * 当发送缓冲区被清空时,如果设置了$onBufferDrain回调,则执行
+     * Emitted when the send buffer becomes empty.
      * @var callback
      */
     public $onBufferDrain = null;
     
     /**
-     * 使用的应用层协议,是协议类的名称
-     * 值类似于 Workerman\\Protocols\\Http
+     * Application layer protocol.
+     * The format is like this Workerman\\Protocols\\Http.
      * @var string
      */
     public $protocol = '';
     
     /**
-     * 属于哪个worker
+     * Which worker belong to.
      * @var Worker
      */
     public $worker = null;
     
     /**
-     * 连接的id,一个自增整数
+     * Connection->id.
      * @var int
      */
     public $id = 0;
     
     /**
-     * 连接的id,为$id的副本,用来清理connections中的连接
+     * A copy of $worker->id which used to clean up the connection in worker->connections
      * @var int
      */
     protected $_id = 0;
     
     /**
-     * 设置当前连接的最大发送缓冲区大小,默认大小为TcpConnection::$defaultMaxSendBufferSize
-     * 当发送缓冲区满时,会尝试触发onBufferFull回调(如果有设置的话)
-     * 如果没设置onBufferFull回调,由于发送缓冲区满,则后续发送的数据将被丢弃,
-     * 并触发onError回调,直到发送缓冲区有空位
-     * 注意 此值可以动态设置
+     * Sets the maximum send buffer size for the current connection.
+     * OnBufferFull callback will be emited When the send buffer is full.
      * @var int
      */
     public $maxSendBufferSize = 1048576;
     
     /**
-     * 默认发送缓冲区大小,设置此属性会影响所有连接的默认发送缓冲区大小
-     * 如果想设置某个连接发送缓冲区的大小,可以单独设置对应连接的$maxSendBufferSize属性
+     * Default send buffer size.
      * @var int
      */
     public static $defaultMaxSendBufferSize = 1048576;
     
     /**
-     * 能接受的最大数据包,为了防止恶意攻击,当数据包的大小大于此值时执行断开
-     * 注意 此值可以动态设置
-     * 例如 Workerman\Connection\TcpConnection::$maxPackageSize=1024000;
+     * Maximum acceptable packet size.
      * @var int
      */
     public static $maxPackageSize = 10485760;
     
     /**
-     * id 记录器
+     * Id recorder.
      * @var int
      */
     protected static $_idRecorder = 1;
     
     /**
-     * 实际的socket资源
+     * Socket
      * @var resource
      */
     protected $_socket = null;
 
     /**
-     * 发送缓冲区
+     * Send buffer.
      * @var string
      */
     protected $_sendBuffer = '';
     
     /**
-     * 接收缓冲区
+     * Receive buffer.
      * @var string
      */
     protected $_recvBuffer = '';
     
     /**
-     * 当前正在处理的数据包的包长(此值是协议的intput方法的返回值)
+     * Current package length.
      * @var int
      */
     protected $_currentPackageLength = 0;
     
     /**
-     * 当前的连接状态
+     * Connection status.
      * @var int
      */
     protected $_status = self::STATUS_ESTABLISH;
     
     /**
-     * 对端的地址 ip+port
-     * 值类似于 192.168.1.100:3698
+     * Remote address.
      * @var string
      */
     protected $_remoteAddress = '';
     
     /**
-     * 是否是停止接收数据
+     * Is paused.
      * @var bool
      */
     protected $_isPaused = false;
     
     /**
-     * 构造函数
+     * Construct.
      * @param resource $socket
      * @param EventInterface $event
      */
     public function __construct($socket, $remote_address = '')
     {
-        // 统计数据
         self::$statistics['connection_count']++;
         $this->id = $this->_id = self::$_idRecorder++;
         $this->_socket = $socket;
@@ -200,14 +191,14 @@ class TcpConnection extends ConnectionInterface
     }
     
     /**
-     * 发送数据给对端
+     * Sends data on the connection.
      * @param string $send_buffer
      * @param bool $raw
      * @return void|boolean
      */
     public function send($send_buffer, $raw = false)
     {
-        // 如果没有设置以原始数据发送,并且有设置协议则按照协议编码
+        // Try to call protocol::encode($send_buffer) before sending.
         if(false === $raw && $this->protocol)
         {
             $parser = $this->protocol;
@@ -218,42 +209,36 @@ class TcpConnection extends ConnectionInterface
             }
         }
         
-        // 如果当前状态是连接中,则把数据放入发送缓冲区
         if($this->_status === self::STATUS_CONNECTING)
         {
             $this->_sendBuffer .= $send_buffer;
             return null;
         }
-        // 如果当前连接是关闭,则返回false
         elseif($this->_status === self::STATUS_CLOSING || $this->_status === self::STATUS_CLOSED)
         {
             return false;
         }
         
-        // 如果发送缓冲区为空,尝试直接发送
+        // Attempt to send data directly.
         if($this->_sendBuffer === '')
         {
-            // 直接发送
             $len = @fwrite($this->_socket, $send_buffer);
-            // 所有数据都发送完毕
+            // send successful.
             if($len === strlen($send_buffer))
             {
                 return true;
             }
-            // 只有部分数据发送成功
+            // Send only part of the data.
             if($len > 0)
             {
-                // 未发送成功部分放入发送缓冲区
                 $this->_sendBuffer = substr($send_buffer, $len);
             }
             else
             {
-                // 如果连接断开
+                // Connection closed?
                 if(!is_resource($this->_socket) || feof($this->_socket))
                 {
-                    // status统计发送失败次数
                     self::$statistics['send_fail']++;
-                    // 如果有设置失败回调,则执行
                     if($this->onError)
                     {
                         try
@@ -266,27 +251,22 @@ class TcpConnection extends ConnectionInterface
                             exit(250);
                         }
                     }
-                    // 销毁连接
                     $this->destroy();
                     return false;
                 }
-                // 连接未断开,发送失败,则把所有数据放入发送缓冲区
                 $this->_sendBuffer = $send_buffer;
             }
-            // 监听对端可写事件
             Worker::$globalEvent->add($this->_socket, EventInterface::EV_WRITE, array($this, 'baseWrite'));
-            // 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
+            // Check if the send buffer is full.
             $this->checkBufferIsFull();
             return null;
         }
         else
         {
-            // 缓冲区已经标记为满,仍然然有数据发送,则丢弃数据包
+            // Buffer has been marked as full but still has data to send the packet is discarded.
             if($this->maxSendBufferSize <= strlen($this->_sendBuffer))
             {
-                // 为status命令统计发送失败次数
                 self::$statistics['send_fail']++;
-                // 如果有设置失败回调,则执行
                 if($this->onError)
                 {
                     try
@@ -301,15 +281,14 @@ class TcpConnection extends ConnectionInterface
                 }
                 return false;
             }
-            // 将数据放入放缓冲区
             $this->_sendBuffer .= $send_buffer;
-            // 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
+            // Check if the send buffer is full.
             $this->checkBufferIsFull();
         }
     }
     
     /**
-     * 获得对端ip
+     * Get remote IP.
      * @return string
      */
     public function getRemoteIp()
@@ -323,7 +302,7 @@ class TcpConnection extends ConnectionInterface
     }
     
     /**
-     * 获得对端端口
+     * Get remote port.
      * @return int
      */
     public function getRemotePort()
@@ -336,7 +315,7 @@ class TcpConnection extends ConnectionInterface
     }
     
     /**
-     * 暂停接收数据,一般用于控制上传流量
+     * Pauses the reading of data. That is onMessage will not be emitted. Useful to throttle back an upload.
      * @return void
      */
     public function pauseRecv()
@@ -346,7 +325,7 @@ class TcpConnection extends ConnectionInterface
     }
     
     /**
-     * 恢复接收数据,一般用户控制上传流量
+     * Resumes reading after a call to pauseRecv.
      * @return void
      */
     public function resumeRecv()
@@ -360,7 +339,7 @@ class TcpConnection extends ConnectionInterface
     }
 
     /**
-     * 当socket可读时的回调
+     * Base read handler.
      * @param resource $socket
      * @return void
      */
@@ -378,23 +357,23 @@ class TcpConnection extends ConnectionInterface
             $this->_recvBuffer .= $buffer;
         }
         
-        // 没有读到数据时检查连接是否断开
+        // Check connection closed.
         if(!$read_data && (!is_resource($socket) || feof($socket)))
         {
             $this->destroy();
             return;
         }
         
-        // 如果设置了协议
+        // If the application layer protocol has been set up.
         if($this->protocol)
         {
            $parser = $this->protocol;
            while($this->_recvBuffer !== '' && !$this->_isPaused)
            {
-               // 当前包的长度已知
+               // The current packet length is known.
                if($this->_currentPackageLength)
                {
-                   // 数据不够一个包
+                   // Data is not enough for a package.
                    if($this->_currentPackageLength > strlen($this->_recvBuffer))
                    {
                        break;
@@ -402,22 +381,22 @@ class TcpConnection extends ConnectionInterface
                }
                else
                {
-                   // 获得当前包长
+                   // Get current package length.
                    $this->_currentPackageLength = $parser::input($this->_recvBuffer, $this);
-                   // 数据不够,无法获得包长
+                   // The packet length is unknown.
                    if($this->_currentPackageLength === 0)
                    {
                        break;
                    }
                    elseif($this->_currentPackageLength > 0 && $this->_currentPackageLength <= self::$maxPackageSize)
                    {
-                       // 数据不够一个包
+                       // Data is not enough for a package.
                        if($this->_currentPackageLength > strlen($this->_recvBuffer))
                        {
                            break;
                        }
                    }
-                   // 包错误
+                   // Wrong package.
                    else
                    {
                        echo 'error package. package_length='.var_export($this->_currentPackageLength, true);
@@ -426,9 +405,9 @@ class TcpConnection extends ConnectionInterface
                    }
                }
                
-               // 数据足够一个包长
+               // The data is enough for a packet.
                self::$statistics['total_request']++;
-               // 当前包长刚好等于buffer的长度
+               // The current packet length is equal to the length of the buffer.
                if(strlen($this->_recvBuffer) === $this->_currentPackageLength)
                {
                    $one_request_buffer = $this->_recvBuffer;
@@ -436,12 +415,12 @@ class TcpConnection extends ConnectionInterface
                }
                else
                {
-                   // 从缓冲区中获取一个完整的包
+                   // Get a full package from the buffer.
                    $one_request_buffer = substr($this->_recvBuffer, 0, $this->_currentPackageLength);
-                   // 将当前包从接受缓冲区中去掉
+                   // Remove the current package from the receive buffer.
                    $this->_recvBuffer = substr($this->_recvBuffer, $this->_currentPackageLength);
                }
-               // 重置当前包长为0
+               // Reset the current packet length to 0.
                $this->_currentPackageLength = 0;
                if(!$this->onMessage)
                {
@@ -449,7 +428,7 @@ class TcpConnection extends ConnectionInterface
                }
                try
                {
-                   // 处理数据包
+                   // Decode request buffer before Emiting onMessage callback.
                    call_user_func($this->onMessage, $this, $parser::decode($one_request_buffer, $this));
                }
                 catch(\Exception $e)
@@ -466,7 +445,7 @@ class TcpConnection extends ConnectionInterface
             return;
         }
         
-        // 没有设置协议,则直接把接收的数据当做一个包处理
+        // Applications protocol is not set.
         self::$statistics['total_request']++;
         if(!$this->onMessage)
         {
@@ -482,12 +461,12 @@ class TcpConnection extends ConnectionInterface
             echo $e;
             exit(250);
         }
-        // 清空缓冲区
+        // Clean receive buffer.
         $this->_recvBuffer = '';
     }
 
     /**
-     * socket可写时的回调
+     * Base write handler.
      * @return void
      */
     public function baseWrite()
@@ -497,7 +476,7 @@ class TcpConnection extends ConnectionInterface
         {
             Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
             $this->_sendBuffer = '';
-            // 发送缓冲区的数据被发送完毕,尝试触发onBufferDrain回调
+            // Try to emit onBufferDrain callback when the send buffer becomes empty. 
             if($this->onBufferDrain)
             {
                 try
@@ -510,7 +489,6 @@ class TcpConnection extends ConnectionInterface
                     exit(250);
                 }
             }
-            // 如果连接状态为关闭,则销毁连接
             if($this->_status === self::STATUS_CLOSING)
             {
                 $this->destroy();
@@ -521,7 +499,6 @@ class TcpConnection extends ConnectionInterface
         {
            $this->_sendBuffer = substr($this->_sendBuffer, $len);
         }
-        // 可写但是写失败,说明连接断开
         else
         {
             self::$statistics['send_fail']++;
@@ -530,7 +507,7 @@ class TcpConnection extends ConnectionInterface
     }
     
     /**
-     * 管道重定向
+     * This method pulls all the data out of a readable stream, and writes it to the supplied destination.
      * @return void
      */
     public function pipe($dest)
@@ -555,7 +532,7 @@ class TcpConnection extends ConnectionInterface
     }
     
     /**
-     * 从缓冲区中消费掉$length长度的数据
+     * Remove $length of data from receive buffer.
      * @param int $length
      * @return void
      */
@@ -565,7 +542,7 @@ class TcpConnection extends ConnectionInterface
     }
 
     /**
-     * 关闭连接
+     * Close connection.
      * @param mixed $data
      * @void
      */
@@ -590,7 +567,7 @@ class TcpConnection extends ConnectionInterface
     }
     
     /**
-     * 获得socket连接
+     * Get the real socket.
      * @return resource
      */
     public function getSocket()
@@ -599,7 +576,7 @@ class TcpConnection extends ConnectionInterface
     }
 
     /**
-     * 检查发送缓冲区是否已满,如果满了尝试触发onBufferFull回调
+     * Check whether the send buffer is full.
      * @return void
      */
     protected function checkBufferIsFull()
@@ -621,29 +598,28 @@ class TcpConnection extends ConnectionInterface
         }
     }
     /**
-     * 销毁连接
+     * Destroy connection.
      * @return void
      */
     public function destroy()
     {
-        // 避免重复调用
+        // Avoid repeated calls.
         if($this->_status === self::STATUS_CLOSED)
         {
             return false;
         }
-        // 删除事件监听
+        // Remove event listener.
         Worker::$globalEvent->del($this->_socket, EventInterface::EV_READ);
         Worker::$globalEvent->del($this->_socket, EventInterface::EV_WRITE);
-        // 关闭socket
+        // Close socket.
         @fclose($this->_socket);
-        // 从连接中删除
+        // Remove from worker->connections.
         if($this->worker)
         {
             unset($this->worker->connections[$this->_id]);
         }
-        // 标记该连接已经关闭
         $this->_status = self::STATUS_CLOSED;
-        // 触发onClose回调
+        // Try to emit onClose callback.
         if($this->onClose)
         {
             try
@@ -656,17 +632,16 @@ class TcpConnection extends ConnectionInterface
                 exit(250);
             }
         }
-        // 清理回调,避免内存泄露
+        // Cleaning up the callback to avoid memory leaks.
         $this->onMessage = $this->onClose = $this->onError = $this->onBufferFull = $this->onBufferDrain = null;
     }
     
     /**
-     * 析构函数
+     * Destruct.
      * @return void
      */
     public function __destruct()
     {
-        // 统计数据
         self::$statistics['connection_count']--;
     }
 }

+ 13 - 14
Connection/UdpConnection.php

@@ -14,44 +14,43 @@
 namespace Workerman\Connection;
 
 /**
- * udp连接类(udp实际上是无连接的,这里是为了保持与TCP接口一致) 
+ * UdpConnection. 
  */
 class UdpConnection extends ConnectionInterface
 {
     /**
-     * 应用层协议
-     * 值类似于 Workerman\\Protocols\\Http
+     * Application layer protocol.
+     * The format is like this Workerman\\Protocols\\Http.
      * @var string
      */
     public $protocol = '';
     
     /**
-     * udp socket 资源
+     * Udp socket.
      * @var resource
      */
     protected $_socket = null;
     
     /**
-     * 对端 ip
+     * Remote ip.
      * @var string
      */
     protected $_remoteIp = '';
     
     /**
-     * 对端 端口
+     * Remote port.
      * @var int
      */
     protected $_remotePort = 0;
     
     /**
-     * 对端 地址
-     * 值类似于 192.168.10.100:3698
+     * Remote address.
      * @var string
      */
     protected $_remoteAddress = '';
 
     /**
-     * 构造函数
+     * Construct.
      * @param resource $socket
      * @param string $remote_address
      */
@@ -62,13 +61,12 @@ class UdpConnection extends ConnectionInterface
     }
     
     /**
-     * 发送数据给对端
+     * Sends data on the connection.
      * @param string $send_buffer
      * @return void|boolean
      */
     public function send($send_buffer, $raw = false)
     {
-        // 如果没有设置以原始数据发送,并且有设置协议则按照协议编码
         if(false === $raw && $this->protocol)
         {
             $parser = $this->protocol;
@@ -82,7 +80,7 @@ class UdpConnection extends ConnectionInterface
     }
     
     /**
-     * 获得对端 ip
+     * Get remote IP.
      * @return string
      */
     public function getRemoteIp()
@@ -95,7 +93,8 @@ class UdpConnection extends ConnectionInterface
     }
     
     /**
-     * 获得对端端口
+     * Get remote port.
+     * @return int
      */
     public function getRemotePort()
     {
@@ -107,7 +106,7 @@ class UdpConnection extends ConnectionInterface
     }
 
     /**
-     * 关闭连接(此处为了保持与TCP接口一致,提供了close方法)
+     * Close connection.
      * @void
      */
     public function close($data = null)

+ 10 - 15
Events/Ev.php

@@ -18,37 +18,32 @@ namespace Workerman\Events;
 class Ev implements EventInterface
 {
     /**
-     * eventBase
-     * @var object
-     */
-    protected $_eventBase = null;
-
-    /**
-     * 所有的事件
+     * All listeners for read/write event.
      * @var array
      */
     protected $_allEvents = array();
 
     /**
-     * 所有的信号事件
+     * Event listeners of signal.
      * @var array
      */
     protected $_eventSignal = array();
 
     /**
-     * 所有的定时事件
+     * All timer event listeners.
      * [func, args, event, flag, time_interval]
      * @var array
      */
     protected $_eventTimer = array();
 
     /**
-     * 定时器id
+     * Timer id.
+     * @var int
      */
     protected static $_timerId = 1;
 
     /**
-     * 添加事件
+     * Add a timer.
      * @see EventInterface::add()
      */
     public function add($fd, $flag, $func, $args=null)
@@ -90,7 +85,7 @@ class Ev implements EventInterface
     }
 
     /**
-     * 删除事件
+     * Remove a timer.
      * @see Events\EventInterface::del()
      */
     public function del($fd ,$flag)
@@ -131,7 +126,7 @@ class Ev implements EventInterface
     }
 
     /**
-     * 定时器回调
+     * Timer callback.
      * @param event $event
      */
     public function timerCallback($event)
@@ -155,7 +150,7 @@ class Ev implements EventInterface
     }
 
     /**
-     * 删除所有定时器
+     * Remove all timers.
      * @return void
      */
     public function clearAllTimer()
@@ -168,7 +163,7 @@ class Ev implements EventInterface
     }
 
     /**
-     * 事件循环
+     * Main loop.
      * @see EventInterface::loop()
      */
     public function loop()

+ 9 - 9
Events/EventInterface.php

@@ -16,37 +16,37 @@ namespace Workerman\Events;
 interface EventInterface
 {
     /**
-     * 读事件
+     * Read event. 
      * @var int
      */
     const EV_READ = 1;
     
     /**
-     * 写事件
+     * Write event.
      * @var int
      */
     const EV_WRITE = 2;
     
     /**
-     * 信号事件
+     * Signal event.
      * @var int
      */
     const EV_SIGNAL = 4;
     
     /**
-     * 连续的定时事件
+     * Timer event.
      * @var int
      */
     const EV_TIMER = 8;
     
     /**
-     * 定时一次
+     * Timer once event.
      * @var int 
      */
     const EV_TIMER_ONCE = 16;
     
     /**
-     * 添加事件回调 
+     * Add event listener to event loop.
      * @param resource $fd
      * @param int $flag
      * @param callable $func
@@ -55,7 +55,7 @@ interface EventInterface
     public function add($fd, $flag, $func, $args = null);
     
     /**
-     * 删除事件回调
+     * Remove event listener from event loop.
      * @param resource $fd
      * @param int $flag
      * @return bool
@@ -63,13 +63,13 @@ interface EventInterface
     public function del($fd, $flag);
     
     /**
-     * 清除所有定时器
+     * Remove all timers.
      * @return void
      */
     public function clearAllTimer();
     
     /**
-     * 事件循环
+     * Main loop.
      * @return void
      */
     public function loop();

+ 7 - 12
Events/Libevent.php

@@ -19,32 +19,32 @@ namespace Workerman\Events;
 class Libevent implements EventInterface
 {
     /**
-     * eventBase
+     * Event base.
      * @var object
      */
     protected $_eventBase = null;
     
     /**
-     * 所有的事件
+     * All listeners for read/write event.
      * @var array
      */
     protected $_allEvents = array();
     
     /**
-     * 所有的信号事件
+     * Event listeners of signal.
      * @var array
      */
     protected $_eventSignal = array();
     
     /**
-     * 所有的定时事件
+     * All timer event listeners.
      * [func, args, event, flag, time_interval]
      * @var array
      */
     protected $_eventTimer = array();
     
     /**
-     * 构造函数
+     * construct
      * @return void
      */
     public function __construct()
@@ -53,7 +53,6 @@ class Libevent implements EventInterface
     }
    
     /**
-     * 添加事件
      * @see EventInterface::add()
      */
     public function add($fd, $flag, $func, $args=array())
@@ -128,7 +127,6 @@ class Libevent implements EventInterface
     }
     
     /**
-     * 删除事件
      * @see Events\EventInterface::del()
      */
     public function del($fd ,$flag)
@@ -170,21 +168,19 @@ class Libevent implements EventInterface
     }
     
     /**
-     * 定时器回调
+     * Timer callback.
      * @param null $_null
      * @param null $_null
      * @param int $timer_id
      */
     protected function timerCallback($_null, $_null, $timer_id)
     {
-        // 如果是连续的定时任务,再把任务加进去
         if($this->_eventTimer[$timer_id][3] === self::EV_TIMER)
         {
             event_add($this->_eventTimer[$timer_id][2], $this->_eventTimer[$timer_id][4]);
         }
         try 
         {
-            // 执行任务
             call_user_func_array($this->_eventTimer[$timer_id][0], $this->_eventTimer[$timer_id][1]);
         }
         catch(\Exception $e)
@@ -199,7 +195,7 @@ class Libevent implements EventInterface
     }
     
     /**
-     * 删除所有定时器
+     * @see Events\EventInterface::clearAllTimer() 
      * @return void
      */
     public function clearAllTimer()
@@ -213,7 +209,6 @@ class Libevent implements EventInterface
      
 
     /**
-     * 事件循环
      * @see EventInterface::loop()
      */
     public function loop()

+ 17 - 30
Events/Select.php

@@ -19,75 +19,74 @@ namespace Workerman\Events;
 class Select implements EventInterface
 {
     /**
-     * 所有的事件
+     * All listeners for read/write event.
      * @var array
      */
     public $_allEvents = array();
     
     /**
-     * 所有信号事件
+     * Event listeners of signal.
      * @var array
      */
     public $_signalEvents = array();
     
     /**
-     * 监听这些描述符的读事件
+     * Fds waiting for read event.
      * @var array
      */
     protected $_readFds = array();
     
     /**
-     * 监听这些描述符的写事件
+     * Fds waiting for write event.
      * @var array
      */
     protected $_writeFds = array();
     
     /**
-     * 任务调度器,最大堆
+     * Timer scheduler.
      * {['data':timer_id, 'priority':run_timestamp], ..}
      * @var SplPriorityQueue
      */
     protected $_scheduler = null;
     
     /**
-     * 定时任务
+     * All timer event listeners.
      * [[func, args, flag, timer_interval], ..]
      * @var array
      */
     protected $_task = array();
     
     /**
-     * 定时器id
+     * Timer id.
      * @var int
      */
     protected $_timerId = 1;
     
     /**
-     * select超时时间,单位:微妙
+     * Select timeout.
      * @var int
      */
     protected $_selectTimeout = 100000000;
     
     /**
-     * 构造函数
+     * Construct.
      * @return void
      */
     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(STREAM_PF_UNIX, 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);
     }
     
     /**
-     * 添加事件及处理函数
      * @see Events\EventInterface::add()
      */
     public function add($fd, $flag, $func, $args = array())
@@ -111,7 +110,6 @@ class Select implements EventInterface
                 break;
             case self::EV_TIMER:
             case self::EV_TIMER_ONCE:
-                // $fd 为 定时的时间间隔,单位为秒,支持小数,能精确到0.001秒
                 $run_time = microtime(true)+$fd;
                 $this->_scheduler->insert($this->_timerId, -$run_time);
                 $this->_task[$this->_timerId] = array($func, (array)$args, $flag, $fd);
@@ -123,7 +121,7 @@ class Select implements EventInterface
     }
     
     /**
-     * 信号处理函数
+     * Signal handler.
      * @param int $signal
      */
     public function signalHandler($signal)
@@ -132,7 +130,6 @@ class Select implements EventInterface
     }
     
     /**
-     * 删除某个描述符的某类事件的监听
      * @see Events\EventInterface::del()
      */
     public function del($fd ,$flag)
@@ -160,7 +157,6 @@ class Select implements EventInterface
                 break;
             case self::EV_TIMER:
             case self::EV_TIMER_ONCE;
-                // $fd_key为要删除的定时器id,即timerId
                 unset($this->_task[$fd_key]);
                 return true;
         }
@@ -168,7 +164,7 @@ class Select implements EventInterface
     }
     
     /**
-     * 检查是否有可执行的定时任务,有的话执行
+     * Tick for timer.
      * @return void
      */
     protected function tick()
@@ -183,21 +179,18 @@ class Select implements EventInterface
             {
                 $this->_scheduler->extract();
                 
-                // 如果任务不存在,则是对应的定时器已经删除
                 if(!isset($this->_task[$timer_id]))
                 {
                     continue;
                 }
                 
-                // 任务数据[func, args, flag, timer_interval]
+                // [func, args, flag, timer_interval]
                 $task_data = $this->_task[$timer_id];
-                // 如果是持续的定时任务,再把任务加到定时队列
                 if($task_data[2] === self::EV_TIMER)
                 {
                     $next_run_time = $time_now+$task_data[3];
                     $this->_scheduler->insert($timer_id, -$next_run_time);
                 }
-                // 尝试执行任务
                 call_user_func_array($task_data[0], $task_data[1]);
                 if(isset($this->_task[$timer_id]) && $task_data[2] === self::EV_TIMER_ONCE)
                 {
@@ -207,7 +200,6 @@ class Select implements EventInterface
             }
             else
             {
-                // 设定超时时间
                 $this->_selectTimeout = ($next_run_time - $time_now)*1000000;
                 return;
             }
@@ -216,8 +208,7 @@ class Select implements EventInterface
     }
     
     /**
-     * 删除所有定时器
-     * @return void
+     * @see Events\EventInterface::clearAllTimer()
      */
     public function clearAllTimer()
     {
@@ -227,7 +218,6 @@ class Select implements EventInterface
     }
     
     /**
-     * 主循环
      * @see Events\EventInterface::loop()
      */
     public function loop()
@@ -235,21 +225,19 @@ class Select implements EventInterface
         $e = null;
         while (1)
         {
-            // 如果有信号,尝试执行信号处理函数
+            // Calls signal handlers for pending signals
             pcntl_signal_dispatch();
             
             $read = $this->_readFds;
             $write = $this->_writeFds;
-            // 等待可读或者可写事件
+            // Waiting read/write/signal/timeout events.
             @stream_select($read, $write, $e, 0, $this->_selectTimeout);
             
-            // 尝试执行定时任务
             if(!$this->_scheduler->isEmpty())
             {
                 $this->tick();
             }
             
-            // 这些描述符可读,执行对应描述符的读回调函数
             if($read)
             {
                 foreach($read as $fd)
@@ -262,7 +250,6 @@ class Select implements EventInterface
                 }
             }
             
-            // 这些描述符可写,执行对应描述符的写回调函数
             if($write)
             {
                 foreach($write as $fd)

+ 5 - 5
Lib/Constants.php

@@ -12,17 +12,17 @@
  * @license http://www.opensource.org/licenses/mit-license.php MIT License
  */
 
-// 如果ini没设置时区,则设置一个默认的
+// Date.timezone
 if(!ini_get('date.timezone') )
 {
     date_default_timezone_set('Asia/Shanghai');
 }
-// 显示错误到终端
+// Display errors.
 ini_set('display_errors', 'on');
-// 报告所有错误
+// Reporting all.
 error_reporting(E_ALL);
 
-// 连接失败
+// For onError callback.
 define('WORKERMAN_CONNECT_FAIL', 1);
-// 发送失败
+// For onError callback.
 define('WORKERMAN_SEND_FAIL', 2);

+ 9 - 8
Lib/Timer.php

@@ -16,7 +16,7 @@ use \Workerman\Events\EventInterface;
 use \Exception;
 
 /**
- * 定时器
+ * Timer.
  * 
  * example:
  * Workerman\Lib\Timer::add($time_interval, callback, array($arg1, $arg2..));
@@ -24,7 +24,7 @@ use \Exception;
 class Timer 
 {
     /**
-     * 基于ALARM信号的任务
+     * Tasks that based on ALARM signal.
      * [
      *   run_time => [[$func, $args, $persistent, time_interval],[$func, $args, $persistent, time_interval],..]],
      *   run_time => [[$func, $args, $persistent, time_interval],[$func, $args, $persistent, time_interval],..]],
@@ -42,7 +42,7 @@ class Timer
     
     
     /**
-     * 初始化
+     * Init.
      * @return void
      */
     public static function init($event = null)
@@ -58,7 +58,7 @@ class Timer
     }
     
     /**
-     * 信号处理函数,只处理ALARM事件
+     * ALARM signal handler.
      * @return void
      */
     public static function signalHandle()
@@ -72,7 +72,7 @@ class Timer
     
     
     /**
-     * 添加一个定时器
+     * Add a timer.
      * @param int $time_interval
      * @param callback $func
      * @param mix $args
@@ -114,7 +114,7 @@ class Timer
     
     
     /**
-     * 尝试触发定时回调
+     * Tick.
      * @return void
      */
     public static function tick()
@@ -155,7 +155,7 @@ class Timer
     }
     
     /**
-     * 删除定时器
+     * Remove a timer.
      * @param $timer_id
      */
     public static function del($timer_id)
@@ -167,7 +167,8 @@ class Timer
     }
     
     /**
-     * 删除所有定时
+     * Remove all timers.
+     * @return void
      */
     public static function delAll()
     {

+ 26 - 24
Protocols/Http.php

@@ -21,7 +21,7 @@ use Workerman\Connection\TcpConnection;
 class Http
 {
     /**
-     * 判断包长
+     * Check the integrity of the package.
      * @param string $recv_buffer
      * @param TcpConnection $connection
      * @return int
@@ -30,7 +30,7 @@ class Http
     {
         if(!strpos($recv_buffer, "\r\n\r\n"))
         {
-            // 无法获得包长,避免客户端传递超大头部的数据包
+            // Judge whether the package length exceeds the limit.
             if(strlen($recv_buffer)>=TcpConnection::$maxPackageSize)
             {
                 $connection->close();
@@ -61,20 +61,20 @@ class Http
     }
     
     /**
-     * 从http数据包中解析$_POST、$_GET、$_COOKIE等 
+     * Parse $_POST、$_GET、$_COOKIE. 
      * @param string $recv_buffer
      * @param TcpConnection $connection
      * @return void
      */
     public static function decode($recv_buffer, TcpConnection $connection)
     {
-        // 初始化
+        // Init.
         $_POST = $_GET = $_COOKIE = $_REQUEST = $_SESSION = $_FILES =  array();
         $GLOBALS['HTTP_RAW_POST_DATA'] = '';
-        // 清空上次的数据
+        // Clear cache.
         HttpCache::$header = array('Connection'=>'Connection: keep-alive');
         HttpCache::$instance = new HttpCache();
-        // 需要设置的变量名
+        // $_SERVER
         $_SERVER = array (
               'QUERY_STRING' => '',
               'REQUEST_METHOD' => '',
@@ -93,7 +93,7 @@ class Http
               'REMOTE_PORT' => '0',
            );
         
-        // 将header分割成数组
+        // Parse headers.
         list($http_header, $http_body) = explode("\r\n\r\n", $recv_buffer, 2);
         $header_data = explode("\r\n", $http_header);
         
@@ -170,7 +170,7 @@ class Http
             }
         }
         
-        // 需要解析$_POST
+        // Parse $_POST.
         if($_SERVER['REQUEST_METHOD'] === 'POST')
         {
             if(isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] === 'multipart/form-data')
@@ -208,14 +208,14 @@ class Http
     }
     
     /**
-     * 编码,增加HTTP头
+     * Http encode.
      * @param string $content
      * @param TcpConnection $connection
      * @return string
      */
     public static function encode($content, TcpConnection $connection)
     {
-        // 没有http-code默认给个
+        // Default http-code.
         if(!isset(HttpCache::$header['Http-Code']))
         {
             $header = "HTTP/1.1 200 OK\r\n";
@@ -308,7 +308,7 @@ class Http
     }
     
     /**
-     * 删除一个header
+     * Remove header.
      * @param string $name
      * @return void
      */
@@ -322,7 +322,7 @@ class Http
     }
     
     /**
-     * 设置cookie
+     * Set cookie.
      * @param string $name
      * @param string $value
      * @param integer $maxage
@@ -361,7 +361,7 @@ class Http
             return true;
         }
         HttpCache::$instance->sessionStarted = true;
-        // 没有sid,则创建一个session文件,生成一个sid
+        // Generate a SID.
         if(!isset($_COOKIE[HttpCache::$sessionName]) || !is_file(HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName]))
         {
             $file_name = tempnam(HttpCache::$sessionPath, 'ses');
@@ -385,7 +385,7 @@ class Http
         {
             HttpCache::$instance->sessionFile = HttpCache::$sessionPath . '/ses' . $_COOKIE[HttpCache::$sessionName];
         }
-        // 有sid则打开文件,读取session值
+        // Read session from session file.
         if(HttpCache::$instance->sessionFile)
         {
             $raw = file_get_contents(HttpCache::$instance->sessionFile);
@@ -397,7 +397,7 @@ class Http
     }
     
     /**
-     * 保存session
+     * Save session.
      * @return bool
      */
     public static function sessionWriteClose()
@@ -418,7 +418,7 @@ class Http
     }
     
     /**
-     * 退出
+     * End, like call exit in php-fpm.
      * @param string $msg
      * @throws \Exception
      */
@@ -436,7 +436,8 @@ class Http
     }
     
     /**
-     * get mime types
+     * Get mime types.
+     * @return string
      */
     public static function getMimeTypesFile()
     {
@@ -444,7 +445,8 @@ class Http
     }
     
      /**
-     * 解析$_FILES
+     * Parse $_FILES.
+     * @return void
      */
     protected static function parseUploadFiles($http_body, $http_post_boundary)
     {
@@ -457,7 +459,7 @@ class Http
         foreach($boundary_data_array as $boundary_data_buffer)
         {
             list($boundary_header_buffer, $boundary_value) = explode("\r\n\r\n", $boundary_data_buffer, 2);
-            // 去掉末尾\r\n
+            // Remove \r\n from the end of buffer.
             $boundary_value = substr($boundary_value, 0, -2);
             foreach (explode("\r\n", $boundary_header_buffer) as $item)
             {
@@ -466,9 +468,10 @@ class Http
                 switch ($header_key)
                 {
                     case "content-disposition":
-                        // 是文件
+                        // Is file data.
                         if(preg_match('/name=".*?"; filename="(.*?)"$/', $header_value, $match))
                         {
+                            // Parse $_FILES.
                             $_FILES[] = array(
                                 'file_name' => $match[1],
                                 'file_data' => $boundary_value,
@@ -476,10 +479,10 @@ class Http
                             );
                             continue;
                         }
-                        // 是post field
+                        // Is post field.
                         else
                         {
-                            // 收集post
+                            // Parse $_POST.
                             if(preg_match('/name="(.*?)"$/', $header_value, $match))
                             {
                                 $_POST[$match[1]] = $boundary_value;
@@ -493,8 +496,7 @@ class Http
 }
 
 /**
- * 解析http协议数据包 缓存先关
- * @author walkor
+ * Http cache for the current http response.
  */
 class HttpCache
 {

+ 9 - 12
Protocols/ProtocolInterface.php

@@ -21,10 +21,11 @@ use \Workerman\Connection\ConnectionInterface;
 interface ProtocolInterface
 {
     /**
-     * 用于分包,即在接收的buffer中返回当前请求的长度(字节)
-     * 如果可以在$recv_buffer中得到请求包的长度则返回长度
-     * 否则返回0,表示需要更多的数据才能得到当前请求包的长度
-     * 如果返回false或者负数,则代表请求不符合协议,则连接会断开
+     * Check the integrity of the package.
+     * Please return the length of package.
+     * If length is unknow please return 0 that mean wating more data.
+     * If the package has something wrong please return false the connection will be closed.
+     * 
      * @param ConnectionInterface $connection
      * @param string $recv_buffer
      * @return int|false
@@ -32,10 +33,8 @@ interface ProtocolInterface
     public static function input($recv_buffer, ConnectionInterface $connection);
     
     /**
-     * 用于请求解包
-     * input返回值大于0,并且WorkerMan收到了足够的数据,则自动调用decode
-     * 然后触发onMessage回调,并将decode解码后的数据传递给onMessage回调的第二个参数
-     * 也就是说当收到完整的客户端请求时,会自动调用decode解码,无需业务代码中手动调用
+     * Decode package and emit onMessage($message) callback, $message is the result that decode returned.
+     * 
      * @param ConnectionInterface $connection
      * @param string $recv_buffer
      * @return mixed
@@ -43,10 +42,8 @@ interface ProtocolInterface
     public static function decode($recv_buffer, ConnectionInterface $connection);
     
     /**
-     * 用于请求打包
-     * 当需要向客户端发送数据即调用$connection->send($data);时
-     * 会自动把$data用encode打包一次,变成符合协议的数据格式,然后再发送给客户端
-     * 也就是说发送给客户端的数据会自动encode打包,无需业务代码中手动调用
+     * Encode package brefore sending to client.
+     * 
      * @param ConnectionInterface $connection
      * @param mixed $data
      * @return string

+ 10 - 15
Protocols/Text.php

@@ -15,57 +15,52 @@ namespace Workerman\Protocols;
 use \Workerman\Connection\TcpConnection;
 
 /**
- * Text协议
- * 以换行为请求结束标记
- * @author walkor <walkor@workerman.net>
+ * Text Protocol.
  */
 class Text
 {
     /**
-     * 检查包的完整性
-     * 如果能够得到包长,则返回包的长度,否则返回0继续等待数据
+     * Check the integrity of the package.
      * @param string $buffer
      */
     public static function input($buffer ,TcpConnection $connection)
     {
-        // 由于没有包头,无法预先知道包长,不能无限制的接收数据,
-        // 所以需要判断当前接收的数据是否超过限定值
+        // Judge whether the package length exceeds the limit.
         if(strlen($buffer)>=TcpConnection::$maxPackageSize)
         {
             $connection->close();
             return 0;
         }
-        // 获得换行字符"\n"位置
+        //  Find the position of  "\n".
         $pos = strpos($buffer, "\n");
-        // 没有换行符,无法得知包长,返回0继续等待数据
+        // No "\n", packet length is unknown, continue to wait for the data so return 0.
         if($pos === false)
         {
             return 0;
         }
-        // 有换行符,返回当前包长,包含换行符
+        // Return the current package length.
         return $pos+1;
     }
     
     /**
-     * 打包,当向客户端发送数据的时候会自动调用
+     * Encode.
      * @param string $buffer
      * @return string
      */
     public static function encode($buffer)
     {
-        // 加上换行
+        // Add "\n"
         return $buffer."\n";
     }
     
     /**
-     * 解包,当接收到的数据字节数等于input返回的值(大于0的值)自动调用
-     * 并传递给onMessage回调函数的$data参数
+     * Decode.
      * @param string $buffer
      * @return string
      */
     public static function decode($buffer)
     {
-        // 去掉换行
+        // Remove "\n"
         return trim($buffer);
     }
 }

+ 50 - 53
Protocols/Websocket.php

@@ -16,55 +16,55 @@ namespace Workerman\Protocols;
 use Workerman\Connection\ConnectionInterface;
 
 /**
- * WebSocket 协议服务端解包和打包
+ * WebSocket protocol.
  */
 class Websocket implements \Workerman\Protocols\ProtocolInterface
 {
     /**
-     * websocket头部最小长度
+     * Minimum head length of websocket protocol.
      * @var int
      */
     const MIN_HEAD_LEN = 6;
     
     /**
-     * websocket blob类型
+     * Websocket blob type.
      * @var char
      */
     const BINARY_TYPE_BLOB = "\x81";
 
     /**
-     * websocket arraybuffer类型
+     * Websocket arraybuffer type.
      * @var char
      */
     const BINARY_TYPE_ARRAYBUFFER = "\x82";
     
     /**
-     * 检查包的完整性
+     * Check the integrity of the package.
      * @param string $buffer
      */
     public static function input($buffer, ConnectionInterface $connection)
     {
-        // 数据长度
+        // Receive length.
         $recv_len = strlen($buffer);
-        // 长度不够
+        // We need more data.
         if($recv_len < self::MIN_HEAD_LEN)
         {
             return 0;
         }
         
-        // 还没有握手
+        // Has not yet completed the handshake.
         if(empty($connection->websocketHandshake))
         {
             return self::dealHandshake($buffer, $connection);
         }
         
-        // $connection->websocketCurrentFrameLength有值说明当前fin为0,则缓冲websocket帧数据
+        // Buffer websocket frame data.
         if($connection->websocketCurrentFrameLength)
         {
-            // 如果当前帧数据未收全,则继续收
+            // We need more frame data.
             if($connection->websocketCurrentFrameLength > $recv_len)
             {
-                // 返回0,因为不清楚完整的数据包长度,需要等待fin=1的帧
+                // Return 0, because it is not clear the full packet length, waiting for the frame of fin=1.
                 return 0;
             }
         }
@@ -76,18 +76,17 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             $opcode = $firstbyte & 0xf;
             switch($opcode)
             {
-                // 附加数据帧 @todo 实现附加数据帧
                 case 0x0:
                     break;
-                // 文本数据帧
+                // Blob type.
                 case 0x1:
                     break;
-                // 二进制数据帧
+                // Arraybuffer type.
                 case 0x2:
                     break;
-                // 关闭的包
+                // Close package.
                 case 0x8:
-                    // 如果有设置onWebSocketClose回调,尝试执行
+                    // Try to emit onWebSocketClose callback.
                     if(isset($connection->onWebSocketClose))
                     {
                         try 
@@ -100,15 +99,15 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                             exit(250);
                         }
                     }
-                    // 默认行为是关闭连接
+                    // Close connection.
                     else
                     {
                         $connection->close();
                     }
                     return 0;
-                // ping的包
+                // Ping package.
                 case 0x9:
-                    // 如果有设置onWebSocketPing回调,尝试执行
+                    // Try to emit onWebSocketPing callback.
                     if(isset($connection->onWebSocketPing))
                     {
                         try 
@@ -121,21 +120,21 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                             exit(250);
                         }
                     }
-                    // 默认发送pong
+                    // Send pong package to client.
                     else 
                     {
                         $connection->send(pack('H*', '8a00'), true);
                     }
-                    // 从接受缓冲区中消费掉该数据包
+                    // Consume data from receive buffer.
                     if(!$data_len)
                     {
                         $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
                         return 0;
                     }
                     break;
-                // pong的包
+                // Pong package.
                 case 0xa:
-                    // 如果有设置onWebSocketPong回调,尝试执行
+                    // Try to emit onWebSocketPong callback.
                     if(isset($connection->onWebSocketPong))
                     {
                         try
@@ -148,21 +147,21 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                             exit(250);
                         }
                     }
-                    // 从接受缓冲区中消费掉该数据包
+                    //  Consume data from receive buffer.
                     if(!$data_len)
                     {
                         $connection->consumeRecvBuffer(self::MIN_HEAD_LEN);
                         return 0;
                     }
                     break;
-                // 错误的opcode 
+                // Wrong opcode. 
                 default :
                     echo "error opcode $opcode and close websocket connection\n";
                     $connection->close();
                     return 0;
             }
             
-            // websocket二进制数据
+            // Calculate packet length.
             $head_len = self::MIN_HEAD_LEN;
             if ($data_len === 126) {
                 $head_len = 8;
@@ -192,7 +191,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             }
         }
         
-        // 收到的数据刚好是一个frame
+        // Received just a frame length data.
         if($connection->websocketCurrentFrameLength == $recv_len)
         {
             self::decode($buffer, $connection);
@@ -200,17 +199,17 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             $connection->websocketCurrentFrameLength = 0;
             return 0;
         }
-        // 收到的数据大于一个frame
+        // The length of the received data is greater than the length of a frame.
         elseif($connection->websocketCurrentFrameLength < $recv_len)
         {
             self::decode(substr($buffer, 0, $connection->websocketCurrentFrameLength), $connection);
             $connection->consumeRecvBuffer($connection->websocketCurrentFrameLength);
             $current_frame_length = $connection->websocketCurrentFrameLength;
             $connection->websocketCurrentFrameLength = 0;
-            // 继续读取下一个frame
+            // Continue to read next frame.
             return self::input(substr($buffer, $current_frame_length), $connection);
         }
-        // 收到的数据不足一个frame
+        // The length of the received data is less than the length of a frame.
         else
         {
             return 0;
@@ -218,7 +217,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
     }
     
     /**
-     * 打包
+     * Websocket encode.
      * @param string $buffer
      * @return string
      */
@@ -227,7 +226,6 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
         $len = strlen($buffer);
         if(empty($connection->websocketType))
         {
-            // 默认是utf8文本格式
             $connection->websocketType = self::BINARY_TYPE_BLOB;
         }
         
@@ -246,16 +244,15 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             $encode_buffer = $first_byte.chr(127).pack("xxxxN", $len).$buffer;
         }
         
-        // 还没握手不能发数据,先将数据缓冲起来,等握手完毕后发送
+        // Handshake not completed so temporary buffer websocket data waiting for send.
         if(empty($connection->websocketHandshake))
         {
             if(empty($connection->tmpWebsocketData))
             {
-                // 临时数据缓冲
                 $connection->tmpWebsocketData = '';
             }
             $connection->tmpWebsocketData .= $encode_buffer;
-            // 返回空,阻止发送
+            // Return empty string.
             return '';
         }
         
@@ -263,7 +260,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
     }
     
     /**
-     * 解包
+     * Websocket decode.
      * @param string $buffer
      * @return string
      */
@@ -298,24 +295,24 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
     }
     
     /**
-     * 处理websocket握手
+     * Websocket handshake.
      * @param string $buffer
      * @param TcpConnection $connection
      * @return int
      */
     protected static function dealHandshake($buffer, $connection)
     {
-        // 握手阶段客户端发送HTTP协议
+        // HTTP protocol.
         if(0 === strpos($buffer, 'GET'))
         {
-            // 判断\r\n\r\n边界
+            // Find \r\n\r\n.
             $heder_end_pos = strpos($buffer, "\r\n\r\n");
             if(!$heder_end_pos)
             {
                 return 0;
             }
             
-            // 解析Sec-WebSocket-Key
+            // Get Sec-WebSocket-Key.
             $Sec_WebSocket_Key = '';
             if(preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match))
             {
@@ -327,28 +324,28 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
                 $connection->close();
                 return 0;
             }
-            // 握手的key
+            // Calculation websocket key.
             $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\r\n";
-            // 标记已经握手
+            // Mark handshake complete..
             $connection->websocketHandshake = true;
-            // 缓冲fin为0的包,直到fin为1
+            // Websocket data buffer.
             $connection->websocketDataBuffer = '';
-            // 当前数据帧的长度,可能是fin为0的帧,也可能是fin为1的帧
+            // Current websocket frame length.
             $connection->websocketCurrentFrameLength = 0;
-            // 当前帧的数据缓冲
+            // Current websocket frame data.
             $connection->websocketCurrentFrameBuffer = '';
-            // 消费掉握手数据,不触发onMessage
+            // Consume handshake data.
             $connection->consumeRecvBuffer(strlen($buffer));
-            // 发送握手数据
+            // Send handshake response.
             $connection->send($handshake_message, true);
             
-            // 握手后有数据要发送
+            // There are data waiting to be sent.
             if(!empty($connection->tmpWebsocketData))
             {
                 $connection->send($connection->tmpWebsocketData, true);
@@ -359,7 +356,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             {
                 $connection->websocketType = self::BINARY_TYPE_BLOB;
             } 
-            // 如果有设置onWebSocketConnect回调,尝试执行
+            // Try to emit onWebSocketConnect callback.
             if(isset($connection->onWebSocketConnect))
             {
                 self::parseHttpHeader($buffer);
@@ -376,7 +373,7 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             }
             return 0;
         }
-        // 如果是flash的policy-file-request
+        // Is flash policy-file-request.
         elseif(0 === strpos($buffer,'<polic'))
         {
             $policy_xml = '<?xml version="1.0"?><cross-domain-policy><site-control permitted-cross-domain-policies="all"/><allow-access-from domain="*" to-ports="*"/></cross-domain-policy>'."\0";
@@ -384,14 +381,14 @@ class Websocket implements \Workerman\Protocols\ProtocolInterface
             $connection->consumeRecvBuffer(strlen($buffer));
             return 0;
         }
-        // 出错
+        // Bad websocket handshake request.
         $connection->send("HTTP/1.1 400 Bad Request\r\n\r\n<b>400 Bad Request</b><br>Invalid handshake data for websocket. ", true);
         $connection->close();
         return 0;
     }
     
     /**
-     * 从header中获取
+     * Parse http header.
      * @param string $buffer
      * @return void
      */

+ 27 - 37
WebServer.php

@@ -18,40 +18,37 @@ use \Workerman\Protocols\Http;
 use \Workerman\Protocols\HttpCache;
 
 /**
- * 
- *  基于Worker实现的一个简单的WebServer
- *  支持静态文件、支持文件上传、支持POST
- *  HTTP协议
+ *  WebServer.
  */
 class WebServer extends Worker
 {
     /**
-     * 默认mime类型
+     * Mime.
      * @var string
      */
     protected static $defaultMimeType = 'text/html; charset=utf-8';
     
     /**
-     * 服务器名到文件路径的转换
+     * Virtual host to path mapping.
      * @var array ['workerman.net'=>'/home', 'www.workerman.net'=>'home/www']
      */
     protected $serverRoot = array();
     
     /**
-     * mime类型映射关系
+     * Mime mapping.
      * @var array
      */
     protected static $mimeTypeMap = array();
     
     
     /**
-     * 用来保存用户设置的onWorkerStart回调
+     * Used to save user OnWorkerStart callback settings.
      * @var callback
      */
     protected $_onWorkerStart = null;
     
     /**
-     * 添加站点域名与站点目录的对应关系,类似nginx的
+     * Add virtual host.
      * @param string $domain
      * @param string $root_path
      * @return void
@@ -62,7 +59,7 @@ class WebServer extends Worker
     }
     
     /**
-     * 构造函数
+     * Construct.
      * @param string $socket_name
      * @param array $context_option
      */
@@ -74,7 +71,7 @@ class WebServer extends Worker
     }
     
     /**
-     * 运行
+     * Run webserver instance.
      * @see Workerman.Worker::run()
      */
     public function run()
@@ -86,7 +83,7 @@ class WebServer extends Worker
     }
     
     /**
-     * 进程启动的时候一些初始化工作
+     * Emit when process start.
      * @throws \Exception
      */
     public function onWorkerStart()
@@ -95,12 +92,12 @@ class WebServer extends Worker
         {
             throw new \Exception('server root not set, please use WebServer::addRoot($domain, $root_path) to set server root path');
         }
-        // 初始化HttpCache
+        // Init HttpCache.
         HttpCache::init();
-        // 初始化mimeMap
+        // Init mimeMap.
         $this->initMimeTypeMap();
         
-        // 尝试执行开发者设定的onWorkerStart回调
+        // Try to emit onWorkerStart callback.
         if($this->_onWorkerStart)
         {
             try
@@ -116,7 +113,7 @@ class WebServer extends Worker
     }
     
     /**
-     * 初始化mimeType
+     * Init mime map.
      * @return void
      */
     public function initMimeTypeMap()
@@ -149,18 +146,14 @@ class WebServer extends Worker
     }
     
     /**
-     * 当接收到完整的http请求后的处理逻辑
-     * 1、如果请求的是以php为后缀的文件,则尝试加载
-     * 2、如果请求的url没有后缀,则尝试加载对应目录的index.php
-     * 3、如果请求的是非php为后缀的文件,尝试读取原始数据并发送
-     * 4、如果请求的文件不存在,则返回404
+     * Emit when http message coming.
      * @param TcpConnection $connection
      * @param mixed $data
      * @return void
      */
     public function onMessage($connection, $data)
     {
-        // 请求的文件
+        // REQUEST_URI.
         $url_info = parse_url($_SERVER['REQUEST_URI']);
         if(!$url_info)
         {
@@ -182,7 +175,6 @@ class WebServer extends Worker
         
         $file = "$root_dir/$path";
         
-        // 对应的php文件不存在则直接使用根目录的index.php
         if($extension === 'php' && !is_file($file))
         {
             $file = "$root_dir/index.php";
@@ -193,10 +185,10 @@ class WebServer extends Worker
             }
         }
         
-        // 请求的文件存在
+        // File exsits.
         if(is_file($file))
         {
-            // 判断是否是站点目录里的文件
+            // Security check.
             if((!($request_realpath = realpath($file)) || !($root_dir_realpath = realpath($root_dir))) || 0 !== strpos($request_realpath, $root_dir_realpath))
             {
                 Http::header('HTTP/1.1 400 Bad Request');
@@ -205,25 +197,24 @@ class WebServer extends Worker
             
             $file = realpath($file);
             
-            // 如果请求的是php文件
+            // Request php file.
             if($extension === 'php')
             {
                 $cwd = getcwd();
                 chdir($root_dir);
                 ini_set('display_errors', 'off');
-                // 缓冲输出
                 ob_start();
-                // 载入php文件
+                // Try to include php file.
                 try 
                 {
-                    // $_SERVER变量
+                    // $_SERVER.
                     $_SERVER['REMOTE_ADDR'] = $connection->getRemoteIp();
                     $_SERVER['REMOTE_PORT'] = $connection->getRemotePort();
                     include $file;
                 }
                 catch(\Exception $e) 
                 {
-                    // 如果不是exit
+                    // Jump_exit?
                     if($e->getMessage() != 'jump_exit')
                     {
                         echo $e;
@@ -236,7 +227,7 @@ class WebServer extends Worker
                 return ;
             }
             
-            // 请求的是静态资源文件
+            // Static resource file request.
             if(isset(self::$mimeTypeMap[$extension]))
             {
                Http::header('Content-Type: '. self::$mimeTypeMap[$extension]);
@@ -246,20 +237,19 @@ class WebServer extends Worker
                 Http::header('Content-Type: '. self::$defaultMimeType);
             }
             
-            // 获取文件信息
+            // Get file stat.
             $info = stat($file);
             
             $modified_time = $info ? date('D, d M Y H:i:s', $info['mtime']) . ' GMT' : '';
             
-            // 如果有$_SERVER['HTTP_IF_MODIFIED_SINCE']
             if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $info)
             {
-                // 文件没有更改则直接304
+                // Http 304.
                 if($modified_time === $_SERVER['HTTP_IF_MODIFIED_SINCE'])
                 {
                     // 304
                     Http::header('HTTP/1.1 304 Not Modified');
-                    // 发送给客户端
+                    // Send nothing but http headers..
                     return $connection->close('');
                 }
             }
@@ -268,14 +258,14 @@ class WebServer extends Worker
             {
                 Http::header("Last-Modified: $modified_time");
             }
-            // 发送给客户端
+            // Send to client.
            return $connection->close(file_get_contents($file));
         }
         else 
         {
             // 404
             Http::header("HTTP/1.1 404 Not Found");
-            return $connection->close('<html><head><title>404 页面不存在</title></head><body><center><h3>404 Not Found</h3></center></body></html>');
+            return $connection->close('<html><head><title>404 File not found</title></head><body><center><h3>404 Not Found</h3></center></body></html>');
         }
     }
 }

Diferenças do arquivo suprimidas por serem muito extensas
+ 151 - 176
Worker.php


Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff