I'm trying to create a simple server using Mojo, that can stream content back to a browser. Basically it would be just a couple lines to send.
I figured using chunked transfer encoding would do the trick, but the client doesn't display any data until the final "0" chunk is sent. I'm guessing there's some sort of buffering happening, and even came across "drain", but can't seem to get it to work. Below is the code in it's simplest form.
In this example, I would expect "HI" to display on the client and 5 seconds later "LO" to display:
Mojo::IOLoop->server({port => 9000} => sub {
my ($loop, $stream) = @_;
$loop = $loop->max_connections(1000);
$stream->on(drain => sub {
print "Drain\n";
# $stream->write("0\r\n\r\n");
});
$stream->on(read => sub {
my ($stream, $bytes) = @_;
print "Bytes: $bytes\n";
$stream->write("HTTP/1.1 200 OK\r\n");
$stream->write("Connection: keep-alive\r\n");
$stream->write("Transfer-Encoding: chunked\r\n");
$stream->write("Content-Type: text/plain\r\n\r\n");
$stream->write("2\r\n");
$stream->write("HI\r\n");
sleep(5);
$stream->write("2\r\n");
$stream->write("LO\r\n");
$stream->write("0\r\n\r\n");
});
});
Mojo::IOLoop->start unless Mojo::IOLoop->is_running;