--
You received this message because you are subscribed to the Google Groups "Mojolicious" group.
To post to this group, send email to mojol...@googlegroups.com.
To unsubscribe from this group, send email to mojolicious...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mojolicious?hl=en.
I have appended code I wrote for the a event-stream client which
might give you some inspiration ... note that the design is
different as the data source (tail -f) only runs once and not for
every client connecting ... in your design every connection gets
its own tail ....
package Signage2;
use Mojo::Base 'Mojolicious';
# This method will run once at server start
sub startup {
my $self = shift;
# Router
my $r = $self->routes;
my $log = $self->log;
$r->get('/' => 'index');
my $stream = $self->launch_arec;
my $loop = Mojo::IOLoop->singleton;
$r->get('/sound' => sub {
my $self = shift;
# Change content type
my $out_stream = $loop->stream($self->tx->connection);
$self->res->headers->content_type('text/event-stream');
# stop mojo from complaining about incomplete page
$self->render_later;
my $read_cb = $stream->on(read => sub {
my ($stream, $chunk) = @_;
while ($chunk =~ m{^(.+)[\r\n]+}g){
$self->write("event:log\ndata:".$1."\n\n");
}
});
my $close = sub {
my $stream = shift;
$self->write("event:log\ndata:Closed\n\n") if $self;
$log->info("closed client connection");
$self->finish;
};
$stream->once(close => $close);
$stream->once(error => $close);
my $unsubscribe = sub {
$stream->unsubscribe(read=>$read_cb);
$log->info("browser gone");
};
# when the connnection is dead, stop writing to it
$out_stream->once(timeout => $unsubscribe);
$out_stream->once(close => $unsubscribe);
});
}
sub launch_tail {
my $self = shift;
# Increase inactivity timeout for connection a bit
my $log = $self->log;
my $pid = open(my $fh,"-|", "tail","-f","$FILE_PATH") ||
die "can't fork: $!";
# Create stream
my $loop = Mojo::IOLoop->singleton;
my $stream = Mojo::IOLoop::Stream->new($fh);
# register with the io loop
my $id = $loop->stream($stream);
$stream->on(error => sub {
my ($stream, $err) = @_;
$loop->remove($id);
$log->error("Stream Error: $err");
});
$stream->on(close => sub {
my $stream = shift;
$log->info("closing connection to tail");
waitpid($pid,0);
$loop->remove($id);
});
$stream->start;
return $stream;
}
1;
Today marcos rebelo wrote:
--
Tobi Oetiker, OETIKER+PARTNER AG, Aarweg 15 CH-4600 Olten, Switzerland
http://it.oetiker.ch to...@oetiker.ch ++41 62 775 9902 / sb: -9900
What am I doing wrong?
open(my $fh, '-|', 'tail', '-f', $FILE_PATH) or die $!;$self->on(finish => sub {close $fh;$fh = undef;} );