2017-10-21 170 views
0

在Web浏览器和服务器的早期阶段,可以创建将数据发送到浏览器的脚本,并且浏览器会在它到达时显示它。如何让现代浏览器在到达时显示行

例如,传统的NPH测试脚本:

#!/usr/local/bin/perl 

$server_protocol = $ENV{'SERVER_PROTOCOL'}; 
$server_software = $ENV{'SERVER_SOFTWARE'}; 
$|=1; 

print "$server_protocol 200 OK", "\n"; 
print "Server: $server_software", "\n"; 
print "Content-type: text/plain", "\n\n"; 

print "OK, Here I go. I am going to count from 1 to 5 !", "\n"; 

for ($loop=1; $loop <= 5; $loop++) { 
    print $loop, "\n"; 
    sleep (2); 
} 

print "All Done!", "\n"; 

exit (0); 

回到在旧的Netscape天浏览器将显示1,2,3,4,5,因为它们到达它们之间2秒。

在现代浏览器(如Chrome)中,只有脚本终止并且所有5行都一次显示,才会看到任何内容。

我可以看到该脚本按预期工作telnet到服务器并运行手动GET命令;每2秒接收一次输出。

有无论如何告诉现代浏览器(也许通过头?)来行事旧的方式,并显示线到达?

回答

0

事实证明,分块模式可行......但在浏览器开始流式传输之前,您需要首先发送一堆数据。

介绍块前的数据,通过试验来确定:

Using "transfer-encoding: chunked", how much data must be sent before browsers start rendering it?

所以所得到的代码将是这样的:

#!/usr/local/bin/perl 

$server_protocol = $ENV{'SERVER_PROTOCOL'}; 
$server_software = $ENV{'SERVER_SOFTWARE'}; 

$|=1; 

print "$server_protocol 200 OK", "\n"; 
print "Server: $server_software", "\n"; 
print "Transfer-Encoding: chunked", "\n"; 
print "Content-type: text/plain", "\n\n"; 

sub chunk { 
    my ($chunk)[email protected]_; 
    printf("%x\n%s\n", length($chunk), $chunk); 
} 

# Send 1K of spaces to convince browsers to display data as it comes 
chunk(" " x 1024); 

chunk("OK, Here I go. I am going to count from 1 to 5 !\r\n"); 

for ($loop=1; $loop <= 5; $loop++) { 
    chunk($loop . "\r\n"); 
    sleep (2); 
} 

chunk("All Done!\r\n"); 

# We need this to tell the client chunking has ended 
chunk(""); 

(由于非SO用户为帮我用这个)

相关问题