Last active
September 28, 2015 23:21
-
-
Save jberger/18023716fe090452daf2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use Mojo::Base -strict; | |
use Mojolicious; | |
use Mojo::UserAgent; | |
use Mojo::IOLoop; | |
package StateNotifier; | |
use Mojo::Base 'Mojo::EventEmitter'; | |
has ua => sub { Mojo::UserAgent->new }; | |
has tx => sub { die 'websocket connection not started' }; | |
sub connect { | |
my $self = shift; | |
my $ua = $self->ua; | |
$ua->websocket('/socket' => sub { | |
my ($ua, $tx) = @_; | |
$self->tx($tx); | |
# send initial state | |
$tx->send($self->get_initial_state . ' sent immediately'); | |
$tx->on(finish => sub { | |
my ($tx, $code, $reason) = @_; | |
say "Websocket closed with status $code"; | |
$self->emit(finish => $code, $reason); | |
}); | |
}); | |
} | |
sub get_initial_state { | |
my $self = shift; | |
return 'Initial state'; | |
} | |
sub send_update { | |
my ($self, $update) = @_; | |
$self->tx->send($update); | |
} | |
sub finish { shift->tx->finish } | |
package main; | |
my $notifier = StateNotifier->new; | |
# a simple "echo to terminal" app to act as a server | |
my $app = Mojolicious->new; | |
$app->routes->websocket('/socket' => sub { | |
my $c = shift; | |
$c->on(text => sub { say $_[1] }); | |
}); | |
$notifier->ua->server->app($app); | |
# setup differential state pusher | |
# presumably this is called by some other service which is getting updates | |
my $t = Mojo::IOLoop->recurring(1 => sub { | |
state $x = 1; | |
$notifier->send_update("Update $x"); | |
$x++; | |
}); | |
$notifier->on(finish => sub { | |
Mojo::IOLoop->remove($t); | |
Mojo::IOLoop->stop; | |
}); | |
$notifier->connect; | |
# just a way to stop the demo | |
local $SIG{INT} = sub { $notifier->finish }; | |
Mojo::IOLoop->start; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment