Skip to content

Instantly share code, notes, and snippets.

@dynax60
Last active December 27, 2015 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dynax60/7373964 to your computer and use it in GitHub Desktop.
Save dynax60/7373964 to your computer and use it in GitHub Desktop.
tail on mojolicious
#!/usr/bin/env perl
use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/lib";
use lib "$FindBin::Bin/lib/mojo/lib";
use Mojolicious::Lite;
use Mojo::IOLoop;
use AnyEvent;
use AnyEvent::Handle;
use File::ReadBackwards;
our $clients = {};
my $rb = File::ReadBackwards->new('/home/null/devel/any/changeme');
my $w; $w = new AnyEvent::Handle
fh => $rb->get_handle,
on_read => sub {
my ($hdl) = @_;
$hdl->push_read(line => sub {
my ($hdl, $line) = @_;
for (keys %$clients) {
$clients->{$_}->app->log->debug("Line: $line");
$clients->{$_}->send($line);
}
});
};
get '/' => 'index';
websocket '/echo' => sub {
my $self = shift;
$self->app->log->debug('WebSocket opened.');
Mojo::IOLoop->stream($self->tx->connection)->timeout(300);
my $id = "$self";
$clients->{$id} = $self;
$self->on(finish => sub {
my ($self,$code,$reason) = @_;
$clients->{$id} = $self;
$self->app->log->debug("WebSocket closed with status $code.");
delete $clients->{$id};
});
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<body>
<script>
var ws = new WebSocket('<%= url_for('echo')->to_abs %>');
ws.onmessage=function(event) {
document.body.innerHTML += event.data +'<br/>';
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment