正如在对上一个问题(PHP External Oauth : how to displaying a waiting message while waiting for callback (not using AJAX) )的回答中所建议的,我正在使用传输编码:分块来在执行某些任务时显示等待消息。我的第一次尝试失败了,我在这个问题“Transfer-Encoding: chunked” header in PHP中找到了解决方案。有一个1024个空格的“填充”。如果没有这个填充,它就不能工作。我用谷歌搜索了一下,但我找不到这个填充物是做什么用的。以下是示例代码(来自相关问题)。
<?php
header('Content-Encoding', 'chunked');
header('Transfer-Encoding', 'chunked');
header('Content-Type', 'text/html');
header('Connection', 'keep-alive');
ob_flush();
flush();
$p = ""; //padding
for ($i=0; $i < 1024; $i++) {
$p .= " ";
};
echo $p;
ob_flush();
flush();
for ($i = 0; $i < 10000; $i++) {
echo "string";
ob_flush();
flush();
sleep(2);
}
?>
有没有人能解释一下为什么它在有“填充”的情况下工作,没有“填充”就不能工作?
发布于 2012-11-26 21:49:40
我不知道这个填充应该做什么,实际上它不应该工作(如果我在这一点上错了,有人可能会启发我)。分块编码的思想是以块的形式发送数据。每个区块由一行包含区块长度的行组成,后跟一个换行符,然后是区块的数据。一个响应可以包含您想要的任意数量的块。所以基本上包含"Hello“的3个块的响应将如下所示:
5 <--- this is the length of the chunk, that is "Hello" == 5 chars
Hello <--- This is a the actual data
<-- an empty line is between the chunks
5
Hello
5
Hello
<-- send two empty lines to end the transmission
所以我会重写成类似这样的代码:
<?php
header('Content-Encoding', 'chunked');
header('Transfer-Encoding', 'chunked');
header('Content-Type', 'text/html');
header('Connection', 'keep-alive');
ob_flush();
flush();
for ($i = 0; $i < 10000; $i++) {
$string = "string";
echo strlen($string)."\r\n"; // this is the length
echo $string."\r\n"; // this is the date
echo "\r\n"; // newline between chunks
ob_flush(); // rinse and repeat
flush();
sleep(2);
}
echo "\r\n"; // send final empty line
ob_flush();
flush();
?>
上面的代码不能在任何情况下工作(例如,字符串包含换行符或非ascii编码),所以你必须根据你的用例来调整它。
https://stackoverflow.com/questions/13565952
复制相似问题