Skip to content

Instantly share code, notes, and snippets.

@throughnothing
Last active December 16, 2015 06:39
Show Gist options
  • Save throughnothing/5393126 to your computer and use it in GitHub Desktop.
Save throughnothing/5393126 to your computer and use it in GitHub Desktop.
Sample Mojolicious EventSource App that gets messages from a Stomp Message Queue
#!/usr/bin/env perl
use Mojolicious::Lite;
use AnyEvent::STOMP;
use List::MoreUtils qw(firstidx);
use Mojo::IOLoop;
# List of connections
my @cons;
# Stomp client
my $client = AnyEvent::STOMP->connect('localhost', 61613, 0, '/topic/streams');
# On new message
$client->reg_cb(MESSAGE => sub {
my (undef, $body, $headers) = @_;
$_->write("event:log\ndata: $body\n\n") for @cons;
});
get '/' => 'index';
get '/events' => sub {
my ($self) = @_;
# Increase inactivity timeout for connection a bit
Mojo::IOLoop->stream($self->tx->connection)->timeout(300);
# Change content type
$self->res->headers->content_type('text/event-stream');
# Push $self to the list of connections
push @cons, $self;
# When the connection closes
$self->on(finish => sub {
# Remove $self from the @cons list
my $idx = firstidx { $_ eq $self } @cons;
splice @cons, $idx, 1;
});
};
app->start;
__DATA__
@@ index.html.ep
<!DOCTYPE html>
<html>
<head><title>LiveLog</title></head>
<body>
<script>
var events = new EventSource('<%= url_for 'events' %>');
// Subscribe to "log" event
events.addEventListener('log', function(event) {
document.body.innerHTML += event.data + '<br/>';
}, false);
</script>
</body>
</html>

Mojolicious EventSource Example App

Dependencies

cpanm -n AnyEvent::STOMP Mojolicious List::MoreUtils

Test Message Queue

For testing you can use POE::Component::MessageQueue (install via cpanm), and just run mq.pl to start a local message queue that these scripts will work on.

Running

./app.pl daemon

Then hit http://localhost:3000 in your browser.

Then Send messages to the queue using:

./send.pl

You should see the stomp messages load in the browser!

#!/usr/bin/env perl
use Net::Stomp;
my $s = Net::Stomp->new({ hostname => 'localhost', port => 61613 });
$s->connect;
while (1) {
$s->send({ destination => '/topic/streams', body => 'test lol ' . rand });
sleep 2;
}
@d-ash
Copy link

d-ash commented Jun 23, 2013

Mojo could be used with AnyEvent only if there is EV available.
So add "use EV;" to be sure it is installed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment