walkor vor 2 Jahren
Ursprung
Commit
de8e9b2b1c
5 geänderte Dateien mit 185 neuen und 136 gelöschten Zeilen
  1. 10 5
      src/Protocols/Frame.php
  2. 44 24
      src/Protocols/Http.php
  3. 6 3
      src/Protocols/Text.php
  4. 51 40
      src/Protocols/Websocket.php
  5. 74 64
      src/Protocols/Ws.php

+ 10 - 5
src/Protocols/Frame.php

@@ -14,6 +14,11 @@
 
 namespace Workerman\Protocols;
 
+use function pack;
+use function strlen;
+use function substr;
+use function unpack;
+
 /**
  * Frame Protocol.
  */
@@ -27,10 +32,10 @@ class Frame
      */
     public static function input(string $buffer): int
     {
-        if (\strlen($buffer) < 4) {
+        if (strlen($buffer) < 4) {
             return 0;
         }
-        $unpackData = \unpack('Ntotal_length', $buffer);
+        $unpackData = unpack('Ntotal_length', $buffer);
         return $unpackData['total_length'];
     }
 
@@ -42,7 +47,7 @@ class Frame
      */
     public static function decode(string $buffer): string
     {
-        return \substr($buffer, 4);
+        return substr($buffer, 4);
     }
 
     /**
@@ -53,7 +58,7 @@ class Frame
      */
     public static function encode(string $data): string
     {
-        $totalLength = 4 + \strlen($data);
-        return \pack('N', $totalLength) . $data;
+        $totalLength = 4 + strlen($data);
+        return pack('N', $totalLength) . $data;
     }
 }

+ 44 - 24
src/Protocols/Http.php

@@ -18,6 +18,25 @@ use Throwable;
 use Workerman\Connection\TcpConnection;
 use Workerman\Protocols\Http\Request;
 use Workerman\Protocols\Http\Response;
+use function clearstatcache;
+use function count;
+use function explode;
+use function filesize;
+use function fopen;
+use function fread;
+use function fseek;
+use function ftell;
+use function in_array;
+use function ini_get;
+use function is_array;
+use function is_object;
+use function key;
+use function preg_match;
+use function strlen;
+use function strpos;
+use function strstr;
+use function substr;
+use function sys_get_temp_dir;
 
 /**
  * Class Http.
@@ -84,10 +103,10 @@ class Http
         if (!isset($buffer[512]) && isset($input[$buffer])) {
             return $input[$buffer];
         }
-        $crlfPos = \strpos($buffer, "\r\n\r\n");
+        $crlfPos = strpos($buffer, "\r\n\r\n");
         if (false === $crlfPos) {
             // Judge whether the package length exceeds the limit.
-            if (\strlen($buffer) >= 16384) {
+            if (strlen($buffer) >= 16384) {
                 $connection->close("HTTP/1.1 413 Payload Too Large\r\n\r\n", true);
                 return 0;
             }
@@ -95,25 +114,25 @@ class Http
         }
 
         $length = $crlfPos + 4;
-        $firstLine = \explode(" ", \strstr($buffer, "\r\n", true), 3);
+        $firstLine = explode(" ", strstr($buffer, "\r\n", true), 3);
 
-        if (!\in_array($firstLine[0], ['GET', 'POST', 'OPTIONS', 'HEAD', 'DELETE', 'PUT', 'PATCH'])) {
+        if (!in_array($firstLine[0], ['GET', 'POST', 'OPTIONS', 'HEAD', 'DELETE', 'PUT', 'PATCH'])) {
             $connection->close("HTTP/1.1 400 Bad Request\r\n\r\n", true);
             return 0;
         }
 
-        $header = \substr($buffer, 0, $crlfPos);
-        $hostHeaderPosition = \strpos($header, "\r\nHost: ");
+        $header = substr($buffer, 0, $crlfPos);
+        $hostHeaderPosition = strpos($header, "\r\nHost: ");
 
         if (false === $hostHeaderPosition && $firstLine[2] === "HTTP/1.1") {
             $connection->close("HTTP/1.1 400 Bad Request\r\n\r\n", true);
             return 0;
         }
 
-        if ($pos = \strpos($header, "\r\nContent-Length: ")) {
-            $length = $length + (int)\substr($header, $pos + 18, 10);
+        if ($pos = strpos($header, "\r\nContent-Length: ")) {
+            $length = $length + (int)substr($header, $pos + 18, 10);
             $hasContentLength = true;
-        } else if (\preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) {
+        } else if (preg_match("/\r\ncontent-length: ?(\d+)/i", $header, $match)) {
             $length = $length + $match[1];
             $hasContentLength = true;
         } else {
@@ -133,7 +152,7 @@ class Http
 
         if (!isset($buffer[512])) {
             $input[$buffer] = $length;
-            if (\count($input) > 512) {
+            if (count($input) > 512) {
                 unset($input[key($input)]);
             }
         }
@@ -164,8 +183,8 @@ class Http
         $connection->request = $request;
         if (true === $cacheable) {
             $requests[$buffer] = $request;
-            if (\count($requests) > 512) {
-                unset($requests[\key($requests)]);
+            if (count($requests) > 512) {
+                unset($requests[key($requests)]);
             }
         }
         return $request;
@@ -185,11 +204,11 @@ class Http
             $request = $connection->request;
             $request->session = $request->connection = $connection->request = null;
         }
-        if (!\is_object($response)) {
+        if (!is_object($response)) {
             $extHeader = '';
             if (isset($connection->headers)) {
                 foreach ($connection->headers as $name => $value) {
-                    if (\is_array($value)) {
+                    if (is_array($value)) {
                         foreach ($value as $item) {
                             $extHeader = "$name: $item\r\n";
                         }
@@ -199,7 +218,7 @@ class Http
                 }
                 $connection->headers = [];
             }
-            $bodyLen = \strlen((string)$response);
+            $bodyLen = strlen((string)$response);
             return "HTTP/1.1 200 OK\r\nServer: workerman\r\n{$extHeader}Connection: keep-alive\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: $bodyLen\r\n\r\n$response";
         }
 
@@ -212,8 +231,8 @@ class Http
             $file = $response->file['file'];
             $offset = $response->file['offset'];
             $length = $response->file['length'];
-            \clearstatcache();
-            $fileSize = (int)\filesize($file);
+            clearstatcache();
+            $fileSize = (int)filesize($file);
             $bodyLen = $length > 0 ? $length : $fileSize - $offset;
             $response->withHeaders([
                 'Content-Length' => $bodyLen,
@@ -224,10 +243,10 @@ class Http
                 $response->header('Content-Range', "bytes $offset-$offsetEnd/$fileSize");
             }
             if ($bodyLen < 2 * 1024 * 1024) {
-                $connection->send((string)$response . file_get_contents($file, false, null, $offset, $bodyLen), true);
+                $connection->send($response . file_get_contents($file, false, null, $offset, $bodyLen), true);
                 return '';
             }
-            $handler = \fopen($file, 'r');
+            $handler = fopen($file, 'r');
             if (false === $handler) {
                 $connection->close(new Response(403, null, '403 Forbidden'));
                 return '';
@@ -247,13 +266,14 @@ class Http
      * @param resource $handler
      * @param int $offset
      * @param int $length
+     * @throws Throwable
      */
     protected static function sendStream(TcpConnection $connection, $handler, int $offset = 0, int $length = 0)
     {
         $connection->context->bufferFull = false;
         $connection->context->streamSending = true;
         if ($offset !== 0) {
-            \fseek($handler, $offset);
+            fseek($handler, $offset);
         }
         $offsetEnd = $offset + $length;
         // Read file content from disk piece by piece and send to client.
@@ -263,7 +283,7 @@ class Http
                 // Read from disk.
                 $size = 1024 * 1024;
                 if ($length !== 0) {
-                    $tell = \ftell($handler);
+                    $tell = ftell($handler);
                     $remainSize = $offsetEnd - $tell;
                     if ($remainSize <= 0) {
                         fclose($handler);
@@ -273,7 +293,7 @@ class Http
                     $size = $remainSize > $size ? $size : $remainSize;
                 }
 
-                $buffer = \fread($handler, $size);
+                $buffer = fread($handler, $size);
                 // Read eof.
                 if ($buffer === '' || $buffer === false) {
                     fclose($handler);
@@ -308,9 +328,9 @@ class Http
             static::$uploadTmpDir = $dir;
         }
         if (static::$uploadTmpDir === '') {
-            if ($uploadTmpDir = \ini_get('upload_tmp_dir')) {
+            if ($uploadTmpDir = ini_get('upload_tmp_dir')) {
                 static::$uploadTmpDir = $uploadTmpDir;
-            } else if ($uploadTmpDir = \sys_get_temp_dir()) {
+            } else if ($uploadTmpDir = sys_get_temp_dir()) {
                 static::$uploadTmpDir = $uploadTmpDir;
             }
         }

+ 6 - 3
src/Protocols/Text.php

@@ -15,6 +15,9 @@
 namespace Workerman\Protocols;
 
 use Workerman\Connection\ConnectionInterface;
+use function rtrim;
+use function strlen;
+use function strpos;
 
 /**
  * Text Protocol.
@@ -31,12 +34,12 @@ class Text
     public static function input(string $buffer, ConnectionInterface $connection): int
     {
         // Judge whether the package length exceeds the limit.
-        if (isset($connection->maxPackageSize) && \strlen($buffer) >= $connection->maxPackageSize) {
+        if (isset($connection->maxPackageSize) && strlen($buffer) >= $connection->maxPackageSize) {
             $connection->close();
             return 0;
         }
         //  Find the position of  "\n".
-        $pos = \strpos($buffer, "\n");
+        $pos = strpos($buffer, "\n");
         // No "\n", packet length is unknown, continue to wait for the data so return 0.
         if ($pos === false) {
             return 0;
@@ -66,6 +69,6 @@ class Text
     public static function decode(string $buffer): string
     {
         // Remove "\n"
-        return \rtrim($buffer, "\r\n");
+        return rtrim($buffer, "\r\n");
     }
 }

+ 51 - 40
src/Protocols/Websocket.php

@@ -19,6 +19,19 @@ use Workerman\Connection\ConnectionInterface;
 use Workerman\Connection\TcpConnection;
 use Workerman\Protocols\Http\Request;
 use Workerman\Worker;
+use function base64_encode;
+use function chr;
+use function floor;
+use function ord;
+use function pack;
+use function preg_match;
+use function sha1;
+use function str_repeat;
+use function stripos;
+use function strlen;
+use function strpos;
+use function substr;
+use function unpack;
 
 /**
  * WebSocket protocol.
@@ -50,7 +63,7 @@ class Websocket
     public static function input(string $buffer, TcpConnection $connection): int
     {
         // Receive length.
-        $recvLen = \strlen($buffer);
+        $recvLen = strlen($buffer);
         // We need more data.
         if ($recvLen < 6) {
             return 0;
@@ -69,8 +82,8 @@ class Websocket
                 return 0;
             }
         } else {
-            $firstbyte = \ord($buffer[0]);
-            $secondbyte = \ord($buffer[1]);
+            $firstbyte = ord($buffer[0]);
+            $secondbyte = ord($buffer[1]);
             $dataLen = $secondbyte & 127;
             $isFinFrame = $firstbyte >> 7;
             $masked = $secondbyte >> 7;
@@ -84,13 +97,13 @@ class Websocket
             $opcode = $firstbyte & 0xf;
             switch ($opcode) {
                 case 0x0:
-                // Blob type.
+                    // Blob type.
                 case 0x1:
-                // Arraybuffer type.
+                    // Arraybuffer type.
                 case 0x2:
-                // Ping package.
+                    // Ping package.
                 case 0x9:
-                // Pong package.
+                    // Pong package.
                 case 0xa:
                     break;
                 // Close package.
@@ -122,7 +135,7 @@ class Websocket
                 if ($headLen > $recvLen) {
                     return 0;
                 }
-                $pack = \unpack('nn/ntotal_len', $buffer);
+                $pack = unpack('nn/ntotal_len', $buffer);
                 $dataLen = $pack['total_len'];
             } else {
                 if ($dataLen === 127) {
@@ -130,13 +143,13 @@ class Websocket
                     if ($headLen > $recvLen) {
                         return 0;
                     }
-                    $arr = \unpack('n/N2c', $buffer);
+                    $arr = unpack('n/N2c', $buffer);
                     $dataLen = $arr['c1'] * 4294967296 + $arr['c2'];
                 }
             }
             $currentFrameLength = $headLen + $dataLen;
 
-            $totalPackageSize = \strlen($connection->context->websocketDataBuffer) + $currentFrameLength;
+            $totalPackageSize = strlen($connection->context->websocketDataBuffer) + $currentFrameLength;
             if ($totalPackageSize > $connection->maxPackageSize) {
                 Worker::safeEcho("error package. package_length=$totalPackageSize\n");
                 $connection->close();
@@ -146,7 +159,7 @@ class Websocket
             if ($isFinFrame) {
                 if ($opcode === 0x9) {
                     if ($recvLen >= $currentFrameLength) {
-                        $pingData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $pingData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
                         $connection->consumeRecvBuffer($currentFrameLength);
                         $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
@@ -162,13 +175,13 @@ class Websocket
                         }
                         $connection->websocketType = $tmpConnectionType;
                         if ($recvLen > $currentFrameLength) {
-                            return static::input(\substr($buffer, $currentFrameLength), $connection);
+                            return static::input(substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
                 } else if ($opcode === 0xa) {
                     if ($recvLen >= $currentFrameLength) {
-                        $pongData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $pongData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
                         $connection->consumeRecvBuffer($currentFrameLength);
                         $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
@@ -183,7 +196,7 @@ class Websocket
                         }
                         $connection->websocketType = $tmpConnectionType;
                         if ($recvLen > $currentFrameLength) {
-                            return static::input(\substr($buffer, $currentFrameLength), $connection);
+                            return static::input(substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
@@ -202,12 +215,12 @@ class Websocket
             return 0;
         } // The length of the received data is greater than the length of a frame.
         elseif ($connection->context->websocketCurrentFrameLength < $recvLen) {
-            static::decode(\substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
+            static::decode(substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
             $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
             $currentFrameLength = $connection->context->websocketCurrentFrameLength;
             $connection->context->websocketCurrentFrameLength = 0;
             // Continue to read next frame.
-            return static::input(\substr($buffer, $currentFrameLength), $connection);
+            return static::input(substr($buffer, $currentFrameLength), $connection);
         } // The length of the received data is less than the length of a frame.
         else {
             return 0;
@@ -223,7 +236,7 @@ class Websocket
      */
     public static function encode(string $buffer, TcpConnection $connection): string
     {
-        $len = \strlen($buffer);
+        $len = strlen($buffer);
         if (empty($connection->websocketType)) {
             $connection->websocketType = static::BINARY_TYPE_BLOB;
         }
@@ -231,12 +244,12 @@ class Websocket
         $firstByte = $connection->websocketType;
 
         if ($len <= 125) {
-            $encodeBuffer = $firstByte . \chr($len) . $buffer;
+            $encodeBuffer = $firstByte . chr($len) . $buffer;
         } else {
             if ($len <= 65535) {
-                $encodeBuffer = $firstByte . \chr(126) . \pack("n", $len) . $buffer;
+                $encodeBuffer = $firstByte . chr(126) . pack("n", $len) . $buffer;
             } else {
-                $encodeBuffer = $firstByte . \chr(127) . \pack("xxxxN", $len) . $buffer;
+                $encodeBuffer = $firstByte . chr(127) . pack("xxxxN", $len) . $buffer;
             }
         }
 
@@ -246,7 +259,7 @@ class Websocket
                 $connection->context->tmpWebsocketData = '';
             }
             // If buffer has already full then discard the current package.
-            if (\strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) {
+            if (strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) {
                 if ($connection->onError) {
                     try {
                         ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package');
@@ -258,7 +271,7 @@ class Websocket
             }
             $connection->context->tmpWebsocketData .= $encodeBuffer;
             // Check buffer is full.
-            if ($connection->maxSendBufferSize <= \strlen($connection->context->tmpWebsocketData)) {
+            if ($connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) {
                 if ($connection->onBufferFull) {
                     try {
                         ($connection->onBufferFull)($connection);
@@ -283,24 +296,23 @@ class Websocket
      */
     public static function decode(string $buffer, TcpConnection $connection): string
     {
-        $firstByte = \ord($buffer[1]);
+        $firstByte = ord($buffer[1]);
         $len = $firstByte & 127;
-        $rsv1 = $firstByte & 64;
 
         if ($len === 126) {
-            $masks = \substr($buffer, 4, 4);
-            $data = \substr($buffer, 8);
+            $masks = substr($buffer, 4, 4);
+            $data = substr($buffer, 8);
         } else {
             if ($len === 127) {
-                $masks = \substr($buffer, 10, 4);
-                $data = \substr($buffer, 14);
+                $masks = substr($buffer, 10, 4);
+                $data = substr($buffer, 14);
             } else {
-                $masks = \substr($buffer, 2, 4);
-                $data = \substr($buffer, 6);
+                $masks = substr($buffer, 2, 4);
+                $data = substr($buffer, 6);
             }
         }
-        $dataLength = \strlen($data);
-        $masks = \str_repeat($masks, \floor($dataLength / 4)) . \substr($masks, 0, $dataLength % 4);
+        $dataLength = strlen($data);
+        $masks = str_repeat($masks, floor($dataLength / 4)) . substr($masks, 0, $dataLength % 4);
         $decoded = $data ^ $masks;
         if ($connection->context->websocketCurrentFrameLength) {
             $connection->context->websocketDataBuffer .= $decoded;
@@ -325,17 +337,16 @@ class Websocket
     public static function dealHandshake(string $buffer, TcpConnection $connection): int
     {
         // HTTP protocol.
-        if (0 === \strpos($buffer, 'GET')) {
+        if (str_starts_with($buffer, 'GET')) {
             // Find \r\n\r\n.
-            $headerEndPos = \strpos($buffer, "\r\n\r\n");
+            $headerEndPos = strpos($buffer, "\r\n\r\n");
             if (!$headerEndPos) {
                 return 0;
             }
             $headerLength = $headerEndPos + 4;
 
             // Get Sec-WebSocket-Key.
-            $SecWebSocketKey = '';
-            if (\preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
+            if (preg_match("/Sec-WebSocket-Key: *(.*?)\r\n/i", $buffer, $match)) {
                 $SecWebSocketKey = $match[1];
             } else {
                 $connection->close("HTTP/1.1 200 WebSocket\r\nServer: workerman/" . Worker::VERSION . "\r\n\r\n<div style=\"text-align:center\"><h1>WebSocket</h1><hr>workerman/" . Worker::VERSION . "</div>",
@@ -343,7 +354,7 @@ class Websocket
                 return 0;
             }
             // Calculation websocket key.
-            $newKey = \base64_encode(\sha1($SecWebSocketKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
+            $newKey = base64_encode(sha1($SecWebSocketKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
             // Handshake response data.
             $handshakeMessage = "HTTP/1.1 101 Switching Protocols\r\n"
                 . "Upgrade: websocket\r\n"
@@ -379,7 +390,7 @@ class Websocket
 
             if ($connection->headers) {
                 foreach ($connection->headers as $header) {
-                    if (\stripos($header, 'Server:') === 0) {
+                    if (stripos($header, 'Server:') === 0) {
                         $hasServerHeader = true;
                     }
                     $handshakeMessage .= "$header\r\n";
@@ -399,8 +410,8 @@ class Websocket
                 $connection->send($connection->context->tmpWebsocketData, true);
                 $connection->context->tmpWebsocketData = '';
             }
-            if (\strlen($buffer) > $headerLength) {
-                return static::input(\substr($buffer, $headerLength), $connection);
+            if (strlen($buffer) > $headerLength) {
+                return static::input(substr($buffer, $headerLength), $connection);
             }
             return 0;
         }

+ 74 - 64
src/Protocols/Ws.php

@@ -15,10 +15,24 @@
 namespace Workerman\Protocols;
 
 use Throwable;
-use Workerman\Worker;
-use Workerman\Timer;
-use Workerman\Connection\TcpConnection;
+use Workerman\Connection\AsyncTcpConnection;
 use Workerman\Connection\ConnectionInterface;
+use Workerman\Timer;
+use Workerman\Worker;
+use function base64_encode;
+use function bin2hex;
+use function floor;
+use function is_array;
+use function ord;
+use function pack;
+use function preg_match;
+use function sha1;
+use function str_repeat;
+use function strlen;
+use function strpos;
+use function substr;
+use function trim;
+use function unpack;
 
 /**
  * Websocket protocol for client.
@@ -43,21 +57,21 @@ class Ws
      * Check the integrity of the package.
      *
      * @param string $buffer
-     * @param TcpConnection $connection
+     * @param AsyncTcpConnection $connection
      * @return int|false
      * @throws Throwable
      */
-    public static function input(string $buffer, TcpConnection $connection): bool|int
+    public static function input(string $buffer, AsyncTcpConnection $connection): bool|int
     {
         if (empty($connection->context->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
         if ($connection->context->handshakeStep === 1) {
             return self::dealHandshake($buffer, $connection);
         }
-        $recvLen = \strlen($buffer);
+        $recvLen = strlen($buffer);
         if ($recvLen < 2) {
             return 0;
         }
@@ -70,8 +84,8 @@ class Ws
             }
         } else {
 
-            $firstbyte = \ord($buffer[0]);
-            $secondbyte = \ord($buffer[1]);
+            $firstbyte = ord($buffer[0]);
+            $secondbyte = ord($buffer[1]);
             $dataLen = $secondbyte & 127;
             $isFinFrame = $firstbyte >> 7;
             $masked = $secondbyte >> 7;
@@ -86,11 +100,11 @@ class Ws
 
             switch ($opcode) {
                 case 0x0:
-                // Blob type.
+                    // Blob type.
                 case 0x1:
-                // Arraybuffer type.
+                    // Arraybuffer type.
                 case 0x2:
-                // Ping package.
+                    // Ping package.
                 case 0x9:
                     // Pong package.
                 case 0xa:
@@ -117,22 +131,22 @@ class Ws
             }
             // Calculate packet length.
             if ($dataLen === 126) {
-                if (\strlen($buffer) < 4) {
+                if (strlen($buffer) < 4) {
                     return 0;
                 }
-                $pack = \unpack('nn/ntotal_len', $buffer);
+                $pack = unpack('nn/ntotal_len', $buffer);
                 $currentFrameLength = $pack['total_len'] + 4;
             } else if ($dataLen === 127) {
-                if (\strlen($buffer) < 10) {
+                if (strlen($buffer) < 10) {
                     return 0;
                 }
-                $arr = \unpack('n/N2c', $buffer);
+                $arr = unpack('n/N2c', $buffer);
                 $currentFrameLength = $arr['c1'] * 4294967296 + $arr['c2'] + 10;
             } else {
                 $currentFrameLength = $dataLen + 2;
             }
 
-            $totalPackageSize = \strlen($connection->context->websocketDataBuffer) + $currentFrameLength;
+            $totalPackageSize = strlen($connection->context->websocketDataBuffer) + $currentFrameLength;
             if ($totalPackageSize > $connection->maxPackageSize) {
                 Worker::safeEcho("error package. package_length=$totalPackageSize\n");
                 $connection->close();
@@ -142,9 +156,9 @@ class Ws
             if ($isFinFrame) {
                 if ($opcode === 0x9) {
                     if ($recvLen >= $currentFrameLength) {
-                        $pingData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $pingData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
                         $connection->consumeRecvBuffer($currentFrameLength);
-                        $tmpConnectionType = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
+                        $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
                         if (isset($connection->onWebSocketPing)) {
                             try {
@@ -157,16 +171,16 @@ class Ws
                         }
                         $connection->websocketType = $tmpConnectionType;
                         if ($recvLen > $currentFrameLength) {
-                            return static::input(\substr($buffer, $currentFrameLength), $connection);
+                            return static::input(substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
 
                 } else if ($opcode === 0xa) {
                     if ($recvLen >= $currentFrameLength) {
-                        $pongData = static::decode(\substr($buffer, 0, $currentFrameLength), $connection);
+                        $pongData = static::decode(substr($buffer, 0, $currentFrameLength), $connection);
                         $connection->consumeRecvBuffer($currentFrameLength);
-                        $tmpConnectionType = isset($connection->websocketType) ? $connection->websocketType : static::BINARY_TYPE_BLOB;
+                        $tmpConnectionType = $connection->websocketType ?? static::BINARY_TYPE_BLOB;
                         $connection->websocketType = "\x8a";
                         // Try to emit onWebSocketPong callback.
                         if (isset($connection->onWebSocketPong)) {
@@ -178,7 +192,7 @@ class Ws
                         }
                         $connection->websocketType = $tmpConnectionType;
                         if ($recvLen > $currentFrameLength) {
-                            return static::input(\substr($buffer, $currentFrameLength), $connection);
+                            return static::input(substr($buffer, $currentFrameLength), $connection);
                         }
                     }
                     return 0;
@@ -196,12 +210,12 @@ class Ws
             return 0;
         } // The length of the received data is greater than the length of a frame.
         elseif ($connection->context->websocketCurrentFrameLength < $recvLen) {
-            self::decode(\substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
+            self::decode(substr($buffer, 0, $connection->context->websocketCurrentFrameLength), $connection);
             $connection->consumeRecvBuffer($connection->context->websocketCurrentFrameLength);
             $currentFrameLength = $connection->context->websocketCurrentFrameLength;
             $connection->context->websocketCurrentFrameLength = 0;
             // Continue to read next frame.
-            return self::input(\substr($buffer, $currentFrameLength), $connection);
+            return self::input(substr($buffer, $currentFrameLength), $connection);
         } // The length of the received data is less than the length of a frame.
         else {
             return 0;
@@ -212,21 +226,21 @@ class Ws
      * Websocket encode.
      *
      * @param string $payload
-     * @param TcpConnection $connection
+     * @param AsyncTcpConnection $connection
      * @return string
+     * @throws Throwable
      */
-    public static function encode(string $payload, TcpConnection $connection): string
+    public static function encode(string $payload, AsyncTcpConnection $connection): string
     {
         if (empty($connection->websocketType)) {
             $connection->websocketType = self::BINARY_TYPE_BLOB;
         }
-        $payload = $payload;
         if (empty($connection->context->handshakeStep)) {
             static::sendHandshake($connection);
         }
 
         $maskKey = "\x00\x00\x00\x00";
-        $length = \strlen($payload);
+        $length = strlen($payload);
 
         if (strlen($payload) < 126) {
             $head = chr(0x80 | $length);
@@ -238,11 +252,11 @@ class Ws
 
         $frame = $connection->websocketType . $head . $maskKey;
         // append payload to frame:
-        $maskKey = \str_repeat($maskKey, \floor($length / 4)) . \substr($maskKey, 0, $length % 4);
+        $maskKey = str_repeat($maskKey, floor($length / 4)) . substr($maskKey, 0, $length % 4);
         $frame .= $payload ^ $maskKey;
         if ($connection->context->handshakeStep === 1) {
             // If buffer has already full then discard the current package.
-            if (\strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) {
+            if (strlen($connection->context->tmpWebsocketData) > $connection->maxSendBufferSize) {
                 if ($connection->onError) {
                     try {
                         ($connection->onError)($connection, ConnectionInterface::SEND_FAIL, 'send buffer full and drop package');
@@ -254,7 +268,7 @@ class Ws
             }
             $connection->context->tmpWebsocketData = $connection->context->tmpWebsocketData . $frame;
             // Check buffer is full.
-            if ($connection->maxSendBufferSize <= \strlen($connection->context->tmpWebsocketData)) {
+            if ($connection->maxSendBufferSize <= strlen($connection->context->tmpWebsocketData)) {
                 if ($connection->onBufferFull) {
                     try {
                         ($connection->onBufferFull)($connection);
@@ -272,19 +286,19 @@ class Ws
      * Websocket decode.
      *
      * @param string $bytes
-     * @param TcpConnection $connection
+     * @param AsyncTcpConnection $connection
      * @return string
      */
-    public static function decode(string $bytes, TcpConnection $connection): string
+    public static function decode(string $bytes, AsyncTcpConnection $connection): string
     {
-        $dataLength = \ord($bytes[1]);
+        $dataLength = ord($bytes[1]);
 
         if ($dataLength === 126) {
-            $decodedData = \substr($bytes, 4);
+            $decodedData = substr($bytes, 4);
         } else if ($dataLength === 127) {
-            $decodedData = \substr($bytes, 10);
+            $decodedData = substr($bytes, 10);
         } else {
-            $decodedData = \substr($bytes, 2);
+            $decodedData = substr($bytes, 2);
         }
         if ($connection->context->websocketCurrentFrameLength) {
             $connection->context->websocketDataBuffer .= $decodedData;
@@ -301,7 +315,9 @@ class Ws
     /**
      * Send websocket handshake data.
      *
+     * @param $connection
      * @return void
+     * @throws Throwable
      */
     public static function onConnect($connection)
     {
@@ -311,9 +327,9 @@ class Ws
     /**
      * Clean
      *
-     * @param TcpConnection $connection
+     * @param AsyncTcpConnection $connection
      */
-    public static function onClose(TcpConnection $connection)
+    public static function onClose(AsyncTcpConnection $connection)
     {
         $connection->context->handshakeStep = null;
         $connection->context->websocketCurrentFrameLength = 0;
@@ -328,11 +344,11 @@ class Ws
     /**
      * Send websocket handshake.
      *
-     * @param TcpConnection $connection
+     * @param AsyncTcpConnection $connection
      * @return void
      * @throws Throwable
      */
-    public static function sendHandshake(TcpConnection $connection)
+    public static function sendHandshake(AsyncTcpConnection $connection)
     {
         if (!empty($connection->context->handshakeStep)) {
             return;
@@ -341,21 +357,21 @@ class Ws
         $port = $connection->getRemotePort();
         $host = $port === 80 ? $connection->getRemoteHost() : $connection->getRemoteHost() . ':' . $port;
         // Handshake header.
-        $connection->context->websocketSecKey = \base64_encode(random_bytes(16));
+        $connection->context->websocketSecKey = base64_encode(random_bytes(16));
         $userHeader = $connection->headers ?? null;
         $userHeaderStr = '';
         if (!empty($userHeader)) {
-            if (\is_array($userHeader)) {
+            if (is_array($userHeader)) {
                 foreach ($userHeader as $k => $v) {
                     $userHeaderStr .= "$k: $v\r\n";
                 }
             } else {
                 $userHeaderStr .= $userHeader;
             }
-            $userHeaderStr = "\r\n" . \trim($userHeaderStr);
+            $userHeaderStr = "\r\n" . trim($userHeaderStr);
         }
         $header = 'GET ' . $connection->getRemoteURI() . " HTTP/1.1\r\n" .
-            (!\preg_match("/\nHost:/i", $userHeaderStr) ? "Host: $host\r\n" : '') .
+            (!preg_match("/\nHost:/i", $userHeaderStr) ? "Host: $host\r\n" : '') .
             "Connection: Upgrade\r\n" .
             "Upgrade: websocket\r\n" .
             (isset($connection->websocketOrigin) ? "Origin: " . $connection->websocketOrigin . "\r\n" : '') .
@@ -373,40 +389,34 @@ class Ws
      * Websocket handshake.
      *
      * @param string $buffer
-     * @param TcpConnection $connection
-     * @return int
+     * @param AsyncTcpConnection $connection
+     * @return bool|int
      * @throws Throwable
      */
-    public static function dealHandshake(string $buffer, TcpConnection $connection): bool|int
+    public static function dealHandshake(string $buffer, AsyncTcpConnection $connection): bool|int
     {
-        $pos = \strpos($buffer, "\r\n\r\n");
+        $pos = strpos($buffer, "\r\n\r\n");
         if ($pos) {
             //checking Sec-WebSocket-Accept
-            if (\preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
-                if ($match[1] !== \base64_encode(\sha1($connection->context->websocketSecKey . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true))) {
-                    Worker::safeEcho("Sec-WebSocket-Accept not match. Header:\n" . \substr($buffer, 0, $pos) . "\n");
+            if (preg_match("/Sec-WebSocket-Accept: *(.*?)\r\n/i", $buffer, $match)) {
+                if ($match[1] !== base64_encode(sha1($connection->context->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;
                 }
             } else {
-                Worker::safeEcho("Sec-WebSocket-Accept not found. Header:\n" . \substr($buffer, 0, $pos) . "\n");
+                Worker::safeEcho("Sec-WebSocket-Accept not found. Header:\n" . substr($buffer, 0, $pos) . "\n");
                 $connection->close();
                 return 0;
             }
 
             // handshake complete
-
-            // Get WebSocket subprotocol (if specified by server)
-            if (\preg_match("/Sec-WebSocket-Protocol: *(.*?)\r\n/i", $buffer, $match)) {
-                $connection->websocketServerProtocol = \trim($match[1]);
-            }
-
             $connection->context->handshakeStep = 2;
             $handshakeResponseLength = $pos + 4;
             // Try to emit onWebSocketConnect callback.
             if (isset($connection->onWebSocketConnect)) {
                 try {
-                    ($connection->onWebSocketConnect)($connection, \substr($buffer, 0, $handshakeResponseLength));
+                    ($connection->onWebSocketConnect)($connection, substr($buffer, 0, $handshakeResponseLength));
                 } catch (Throwable $e) {
                     Worker::stopAll(250, $e);
                 }
@@ -414,7 +424,7 @@ class Ws
             // Headbeat.
             if (!empty($connection->websocketPingInterval)) {
                 $connection->context->websocketPingTimer = Timer::add($connection->websocketPingInterval, function () use ($connection) {
-                    if (false === $connection->send(\pack('H*', '898000000000'), true)) {
+                    if (false === $connection->send(pack('H*', '898000000000'), true)) {
                         Timer::del($connection->context->websocketPingTimer);
                         $connection->context->websocketPingTimer = null;
                     }
@@ -426,8 +436,8 @@ class Ws
                 $connection->send($connection->context->tmpWebsocketData, true);
                 $connection->context->tmpWebsocketData = '';
             }
-            if (\strlen($buffer) > $handshakeResponseLength) {
-                return self::input(\substr($buffer, $handshakeResponseLength), $connection);
+            if (strlen($buffer) > $handshakeResponseLength) {
+                return self::input(substr($buffer, $handshakeResponseLength), $connection);
             }
         }
         return 0;