用户登录
用户注册

分享至

php下HTTP Response中的Chunked编码实现方法

  • 作者: 嗫?暁雲?
  • 来源: 51数据库
  • 2021-09-29
进行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 = <hex excluding "0">
  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 ) );
}
软件
前端设计
程序设计
Java相关