php下HTTP Response中的Chunked編碼實現方法_PHP教程

來源:互聯網
上載者:User
進行Chunked編碼傳輸的HTTP Response會在訊息頭部設定:
Transfer-Encoding: chunked
表示Content Body將用Chunked編碼傳輸內容。
Chunked編碼使用若干個Chunk串聯而成,由一個標明長度為0的chunk標示結束。每個Chunk分為頭部和本文兩部分,頭部內容指定下一段本文的字元總數(十六進位的數字)和數量單位(一般不寫),本文部分就是指定長度的實際內容,兩部分之間用斷行符號換行(CRLF)隔開。在最後一個長度為0的Chunk中的內容是稱為footer的內容,是一些附加的Header資訊(通常可以直接忽略)。具體的Chunk編碼格式如下:
複製代碼 代碼如下:
  Chunked-Body = *chunk
         "0" CRLF
         footer
         CRLF
  chunk = chunk-size [ chunk-ext ] CRLF
       chunk-data CRLF
  hex-no-zero =
  chunk-size = hex-no-zero *HEX
  chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-value ] )
  chunk-ext-name = token
  chunk-ext-val = token | quoted-string
  chunk-data = chunk-size(OCTET)
  footer = *entity-header

RFC文檔中的Chunked解碼過程如下:
複製代碼 代碼如下:
  length := 0
  read chunk-size, chunk-ext (if any) and CRLF
  while (chunk-size > 0) {
  read chunk-data and CRLF
  append chunk-data to entity-body
  length := length + chunk-size
  read chunk-size and CRLF
  }
  read entity-header
  while (entity-header not empty) {
  append entity-header to existing header fields
  read entity-header
  }
  Content-Length := length
  Remove "chunked" from Transfer-Encoding

最後提供一段PHP版本的chunked解碼代碼:
複製代碼 代碼如下:
$chunk_size = (integer)hexdec(fgets( $socket_fd, 4096 ) );
while(!feof($socket_fd) && $chunk_size > 0) {
$bodyContent .= fread( $socket_fd, $chunk_size );
fread( $socket_fd, 2 ); // skip \r\n
$chunk_size = (integer)hexdec(fgets( $socket_fd, 4096 ) );
}

http://www.bkjia.com/PHPjc/319767.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/319767.htmlTechArticle進行Chunked編碼傳輸的HTTP Response會在訊息頭部設定: Transfer-Encoding: chunked 表示Content Body將用Chunked編碼傳輸內容。 Chunked編碼使用若干個Chun...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.