#!/usr/bin/perl

use strict;
use warnings;
use IO::Handle;
use CGI qw(:standard);

# Since this is a long-running CGI, we should handle SIGPIPE, in case
# the stop button is pushed.
$SIG{"PIPE"} = sub { die; };

my $fh = new IO::Handle;
$fh->fdopen(fileno(STDOUT),"w") || die "Couldn't open STDOUT: $!";

$fh->print(header);

my $begin = <<'END';
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-strict.dtd">
<html><head><title></title></head><body>
END

chomp $begin;

# Internet Explorer seems to need about 256 bytes of data before push
# begins to work.  Safari seems to need about 1024 bytes.  Pad the
# opening html tags with whitespace, to ensure the browser can stream.
my $whitespace = " " x (1024 - length $begin);

$begin =~ s/<body>$/$whitespace<body>/s;

$fh->print($begin);

while (1) {
  $fh->print("<p>" . int(rand(100)) . "</p>");
  $fh->flush;
  sleep 1;
}

$fh->print("</body></html>");


